Search in sources :

Example 1 with Notification

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()) {
    }
}
Also used : APIMConfigurations(org.wso2.carbon.apimgt.core.configuration.models.APIMConfigurations) NotificationException(org.wso2.carbon.apimgt.core.exception.NotificationException) NotifierConfigurations(org.wso2.carbon.apimgt.core.configuration.models.NotifierConfigurations) Properties(java.util.Properties) Map(java.util.Map) Notifier(org.wso2.carbon.apimgt.core.impl.Notifier)

Example 2 with Notification

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());
}
Also used : EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent)

Example 3 with Notification

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.");
    }
}
Also used : EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException)

Example 4 with Notification

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);
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 5 with Notification

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");
    }
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) Test(org.junit.Test)

Aggregations

HashMap (java.util.HashMap)31 IdentityEventException (org.wso2.carbon.identity.event.IdentityEventException)25 UserRecoveryData (org.wso2.carbon.identity.recovery.model.UserRecoveryData)21 UserRecoveryDataStore (org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore)18 IdentityRecoveryException (org.wso2.carbon.identity.recovery.IdentityRecoveryException)17 UserStoreException (org.wso2.carbon.user.api.UserStoreException)17 Event (org.wso2.carbon.identity.event.event.Event)14 IdentityException (org.wso2.carbon.identity.base.IdentityException)13 User (org.wso2.carbon.identity.application.common.model.User)10 NotificationResponseBean (org.wso2.carbon.identity.recovery.bean.NotificationResponseBean)10 ArrayList (java.util.ArrayList)8 QName (javax.xml.namespace.QName)8 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)8 Map (java.util.Map)7 Test (org.testng.annotations.Test)7 Property (org.wso2.carbon.identity.recovery.model.Property)7 NotificationChannels (org.wso2.carbon.identity.governance.service.notification.NotificationChannels)6 UserStoreException (org.wso2.carbon.user.core.UserStoreException)6 NotificationException (org.wso2.carbon.apimgt.impl.notification.exception.NotificationException)5 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)5