use of org.wso2.carbon.identity.mgt.mail.Notification in project carbon-apimgt by wso2.
the class NotificationExecutor method sendAsyncNotifications.
/**
* Executes the notifer classes in separtate threads.
*
* @param notificationDTO
* @throws org.wso2.carbon.apimgt.core.exception.NotificationException
*/
public void sendAsyncNotifications(NotificationDTO notificationDTO) throws NotificationException {
List<NotifierConfigurations> notifierConfigurations = new APIMConfigurations().getNotificationConfigurations().getNewVersionNotifierConfiguration().getNotifierConfigurations();
if (notificationDTO.getType().equalsIgnoreCase(NotifierConstants.NOTIFICATION_TYPE_NEW_VERSION)) {
for (NotifierConfigurations listItem : notifierConfigurations) {
String executorClass = listItem.getExecutorClass();
Map property = listItem.getPropertyList();
Properties prop = notificationDTO.getProperties();
prop.putAll(property);
notificationDTO.setProperties(prop);
// starting Notifier threads
if (executorClass != null && !executorClass.isEmpty()) {
Notifier notifier;
try {
notifier = (Notifier) APIUtils.getClassForName(executorClass).newInstance();
} catch (InstantiationException e) {
throw new NotificationException("Instantiation Error while Initializing the notifier class", e);
} catch (IllegalAccessException e) {
throw new NotificationException("IllegalAccess Error while Initializing the notifier class", e);
} catch (ClassNotFoundException e) {
throw new NotificationException("ClassNotFound Error while Initializing the notifier class", e);
}
notifier.setNotificationDTO(notificationDTO);
executor.execute(notifier);
} else {
if (log.isDebugEnabled()) {
log.debug("Class " + executorClass + " Empty Or Null");
}
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Notification Type Does Not match with " + NotifierConstants.NOTIFICATION_TYPE_NEW_VERSION);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
use of org.wso2.carbon.identity.mgt.mail.Notification in project carbon-apimgt by wso2.
the class WebhooksSubscriptionEventHandler method sendSubscriptionNotificationOnRealtime.
/**
* Method to publish the subscription request on to the realtime message broker
*
* @param event realtime notification data read from the event
*/
private void sendSubscriptionNotificationOnRealtime(WebhooksSubscriptionEvent event, boolean isSuccess) {
Object[] objects = new Object[] { event.getApiUUID(), event.getApiName(), event.getApiContext(), event.getApiVersion(), event.getAppID(), event.getTenantDomain(), event.getTenantId(), event.getCallback(), event.getTopic(), event.getMode(), event.getSecret(), event.getExpiryTime(), event.getSubscriberName(), event.getApplicationTier(), event.getTier(), event.getApiTier(), !isSuccess };
EventPublisherEvent asyncWebhooksEvent = new EventPublisherEvent(APIConstants.WEBHOOKS_SUBSCRIPTION_STREAM_ID, System.currentTimeMillis(), objects);
APIUtil.publishEvent(EventPublisherType.ASYNC_WEBHOOKS, asyncWebhooksEvent, asyncWebhooksEvent.toString());
}
use of org.wso2.carbon.identity.mgt.mail.Notification in project carbon-apimgt by wso2.
the class APIManagerComponent method configureNotificationEventPublisher.
/**
* Method to configure wso2event type event adapter to be used for event notification.
*/
private void configureNotificationEventPublisher() throws APIManagementException {
Map<String, String> properties = new HashMap<>();
if (ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() != null) {
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
if (configuration.getEventHubConfigurationDto().getEventHubPublisherConfiguration() != null && configuration.getEventHubConfigurationDto().isEnabled()) {
EventHubConfigurationDto eventHubConfigurationDto = configuration.getEventHubConfigurationDto();
EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = eventHubConfigurationDto.getEventHubPublisherConfiguration();
properties.put(APIConstants.RECEIVER_URL, eventHubPublisherConfiguration.getReceiverUrlGroup());
properties.put(APIConstants.AUTHENTICATOR_URL, eventHubPublisherConfiguration.getAuthUrlGroup());
properties.put(APIConstants.USERNAME, eventHubConfigurationDto.getUsername());
properties.put(APIConstants.PASSWORD, eventHubConfigurationDto.getPassword());
properties.put(APIConstants.PROTOCOL, eventHubPublisherConfiguration.getType());
properties.put(APIConstants.PUBLISHING_MODE, APIConstants.NON_BLOCKING);
properties.put(APIConstants.PUBLISHING_TIME_OUT, "0");
for (String key : eventHubPublisherConfiguration.getProperties().keySet()) {
properties.put(key, eventHubPublisherConfiguration.getProperties().get(key));
}
properties.put(APIConstants.IS_ENABLED, Boolean.toString(configuration.getEventHubConfigurationDto().isEnabled()));
try {
ServiceReferenceHolder.getInstance().getEventPublisherFactory().configure(properties);
} catch (EventPublisherException e) {
throw new APIManagementException(e);
}
} else {
log.info("Wso2Event Publisher not enabled.");
}
} else {
log.info("api-manager.xml not loaded. Wso2Event Publisher will not be enabled.");
}
}
use of org.wso2.carbon.identity.mgt.mail.Notification in project carbon-apimgt by wso2.
the class APIConsumerImpl method addSubscription.
@Override
public SubscriptionResponse addSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application) throws APIManagementException {
API api = null;
APIProduct product = null;
Identifier identifier = null;
int apiId;
String apiUUID;
final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
String state;
String apiContext;
if (isApiProduct) {
product = apiTypeWrapper.getApiProduct();
state = product.getState();
identifier = product.getId();
apiId = product.getProductId();
apiUUID = product.getUuid();
apiContext = product.getContext();
} else {
api = apiTypeWrapper.getApi();
state = api.getStatus();
identifier = api.getId();
apiId = api.getId().getId();
apiUUID = api.getUuid();
apiContext = api.getContext();
}
WorkflowResponse workflowResponse = null;
String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
checkSubscriptionAllowed(apiTypeWrapper);
int subscriptionId;
if (APIConstants.PUBLISHED.equals(state) || APIConstants.PROTOTYPED.equals(state)) {
subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, tenantAwareUsername);
boolean isTenantFlowStarted = false;
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
}
String applicationName = application.getName();
try {
WorkflowExecutor addSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
workflowDTO.setStatus(WorkflowStatus.CREATED);
workflowDTO.setCreatedTime(System.currentTimeMillis());
workflowDTO.setTenantDomain(tenantDomain);
workflowDTO.setTenantId(tenantId);
workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
workflowDTO.setApiName(identifier.getName());
workflowDTO.setApiContext(apiContext);
workflowDTO.setApiVersion(identifier.getVersion());
workflowDTO.setApiProvider(identifier.getProviderName());
workflowDTO.setTierName(identifier.getTier());
workflowDTO.setRequestedTierName(identifier.getTier());
workflowDTO.setApplicationName(applicationName);
workflowDTO.setApplicationId(application.getId());
workflowDTO.setSubscriber(userId);
Tier tier = null;
Set<Tier> policies = Collections.emptySet();
if (!isApiProduct) {
policies = api.getAvailableTiers();
} else {
policies = product.getAvailableTiers();
}
for (Tier policy : policies) {
if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
tier = policy;
}
}
boolean isMonetizationEnabled = false;
if (api != null) {
isMonetizationEnabled = api.getMonetizationStatus();
// check whether monetization is enabled for API and tier plan is commercial
if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
} else {
workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
}
} else {
isMonetizationEnabled = product.getMonetizationStatus();
// check whether monetization is enabled for API and tier plan is commercial
if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
} else {
workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
}
}
} catch (WorkflowException e) {
// If the workflow execution fails, roll back transaction by removing the subscription entry.
apiMgtDAO.removeSubscriptionById(subscriptionId);
log.error("Could not execute Workflow", e);
throw new APIManagementException("Could not execute Workflow", e);
} finally {
if (isTenantFlowStarted) {
endTenantFlow();
}
}
// to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
// the response should have {"Status":"REJECTED"} in the json payload for this to work.
boolean subscriptionRejected = false;
String subscriptionStatus = null;
String subscriptionUUID = "";
SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);
if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
try {
JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
subscriptionRejected = true;
subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
}
} catch (ParseException e) {
log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
}
}
if (!subscriptionRejected) {
subscriptionStatus = addedSubscription.getSubStatus();
subscriptionUUID = addedSubscription.getUUID();
JSONObject subsLogObject = new JSONObject();
subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
if (workflowResponse == null) {
workflowResponse = new GeneralWorkflowResponse();
}
}
// get the workflow state once the executor is executed.
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
// only send the notification if approved
// wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
if (wfDTO != null) {
if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
}
} else {
SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
}
if (log.isDebugEnabled()) {
String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + applicationName;
log.debug(logMessage);
}
return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
} else {
throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
}
}
use of org.wso2.carbon.identity.mgt.mail.Notification in project carbon-apimgt by wso2.
the class NewAPIVersionEmailNotifierTest method testShouldLoadMessageTemplateWhenDtoValid.
@Test
public void testShouldLoadMessageTemplateWhenDtoValid() throws RegistryException {
Resource resource = Mockito.mock(Resource.class);
NewAPIVersionEmailNotifier emailNotifier = new NewAPIVersionEmailNotifier() {
@Override
protected Registry getConfigSystemRegistry(int tenantId) throws RegistryException {
return registry;
}
};
Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true).thenReturn(false);
Mockito.when(registry.get(Mockito.anyString())).thenReturn(resource);
Mockito.when(resource.getContent()).thenReturn("<html>$1-$2-$3</html>".getBytes());
try {
NotificationDTO notification = emailNotifier.loadMessageTemplate(notificationDTO);
Assert.assertFalse(!notification.getMessage().contains(API_NAME));
// should use dto template if resource not found in registry
notification = emailNotifier.loadMessageTemplate(notificationDTO);
Assert.assertFalse(!notification.getMessage().contains(API_NAME));
} catch (NotificationException e) {
Assert.fail("Should not throw any exceptions");
}
}
Aggregations