Search in sources :

Example 96 with Subscription

use of org.wso2.carbon.apimgt.api.model.webhooks.Subscription in project carbon-apimgt by wso2.

the class ApiMgtDAO method getSubscribersOfProvider.

/**
 * This method returns the set of Subscribers for given provider
 *
 * @param providerName name of the provider
 * @return Set<Subscriber>
 * @throws APIManagementException if failed to get subscribers for given provider
 */
@Deprecated
public Set<Subscriber> getSubscribersOfProvider(String providerName) throws APIManagementException {
    Set<Subscriber> subscribers = new HashSet<Subscriber>();
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    try {
        String sqlQuery = SQLConstants.GET_SUBSCRIBERS_OF_PROVIDER_SQL;
        connection = APIMgtDBUtil.getConnection();
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
        result = ps.executeQuery();
        while (result.next()) {
            // Subscription table should have API_VERSION AND API_PROVIDER
            Subscriber subscriber = new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_EMAIL_ADDRESS));
            subscriber.setName(result.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID));
            subscriber.setSubscribedDate(result.getDate(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED));
            subscribers.add(subscriber);
        }
    } catch (SQLException e) {
        handleException("Failed to subscribers for :" + providerName, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
    return subscribers;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 97 with Subscription

use of org.wso2.carbon.apimgt.api.model.webhooks.Subscription in project carbon-apimgt by wso2.

the class ApiMgtDAO method updateSubscription.

/**
 * This method is used to update the subscription
 *
 * @param identifier    APIIdentifier
 * @param subStatus     Subscription Status[BLOCKED/UNBLOCKED]
 * @param applicationId Application id
 * @param organization  Organization
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update subscriber
 */
public void updateSubscription(APIIdentifier identifier, String subStatus, int applicationId, String organization) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    PreparedStatement updatePs = null;
    int apiId = -1;
    try {
        conn = APIMgtDBUtil.getConnection();
        conn.setAutoCommit(false);
        String getApiQuery = SQLConstants.GET_API_ID_SQL;
        ps = conn.prepareStatement(getApiQuery);
        ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        ps.setString(2, identifier.getApiName());
        ps.setString(3, identifier.getVersion());
        resultSet = ps.executeQuery();
        if (resultSet.next()) {
            apiId = resultSet.getInt("API_ID");
        }
        if (apiId == -1) {
            String msg = "Unable to get the API ID for: " + identifier;
            log.error(msg);
            throw new APIManagementException(msg);
        }
        String subsCreateStatus = getSubscriptionCreaeteStatus(identifier, applicationId, organization, conn);
        if (APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subsCreateStatus)) {
            deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
        }
        // This query to update the AM_SUBSCRIPTION table
        String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_OF_APPLICATION_SQL;
        // Updating data to the AM_SUBSCRIPTION table
        updatePs = conn.prepareStatement(sqlQuery);
        updatePs.setString(1, subStatus);
        updatePs.setString(2, identifier.getProviderName());
        updatePs.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
        updatePs.setInt(4, apiId);
        updatePs.setInt(5, applicationId);
        updatePs.execute();
        // finally commit transaction
        conn.commit();
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback the add subscription ", e1);
            }
        }
        handleException("Failed to update subscription data ", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
        APIMgtDBUtil.closeAllConnections(updatePs, null, null);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 98 with Subscription

use of org.wso2.carbon.apimgt.api.model.webhooks.Subscription in project carbon-apimgt by wso2.

the class ApiMgtDAO method removeSubscription.

/**
 * Removes the subscription entry from AM_SUBSCRIPTIONS for identifier.
 *
 * @param identifier    Identifier
 * @param applicationId ID of the application which has the subscription
 * @throws APIManagementException
 */
public void removeSubscription(Identifier identifier, int applicationId) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    int id = -1;
    String uuid;
    try {
        conn = APIMgtDBUtil.getConnection();
        conn.setAutoCommit(false);
        String subscriptionUUIDQuery = SQLConstants.GET_SUBSCRIPTION_UUID_SQL;
        if (identifier.getId() > 0) {
            id = identifier.getId();
        } else if (identifier instanceof APIIdentifier) {
            String apiUuid;
            if (identifier.getUUID() != null) {
                apiUuid = identifier.getUUID();
            } else {
                apiUuid = getUUIDFromIdentifier((APIIdentifier) identifier);
            }
            id = getAPIID(apiUuid, conn);
        } else if (identifier instanceof APIProductIdentifier) {
            id = ((APIProductIdentifier) identifier).getProductId();
        }
        ps = conn.prepareStatement(subscriptionUUIDQuery);
        ps.setInt(1, id);
        ps.setInt(2, applicationId);
        resultSet = ps.executeQuery();
        if (resultSet.next()) {
            uuid = resultSet.getString("UUID");
            SubscribedAPI subscribedAPI = new SubscribedAPI(uuid);
            removeSubscription(subscribedAPI, conn);
        } else {
            throw new APIManagementException("UUID does not exist for the given apiId:" + id + " and " + "application id:" + applicationId);
        }
        conn.commit();
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                log.error("Failed to rollback the add subscription ", ex);
            }
        }
        handleException("Failed to add subscriber data ", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 99 with Subscription

use of org.wso2.carbon.apimgt.api.model.webhooks.Subscription in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPIsInExternalAPIStores.

/**
 * Update the API to external APIStores and database
 *
 * @param api         The API which need to published
 * @param apiStoreSet The APIStores set to which need to publish API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException If failed to update subscription status
 */
@Override
public boolean updateAPIsInExternalAPIStores(API api, Set<APIStore> apiStoreSet, boolean apiOlderVersionExist) throws APIManagementException {
    Set<APIStore> publishedStores = getPublishedExternalAPIStores(api.getUuid());
    Set<APIStore> notPublishedAPIStores = new HashSet<APIStore>();
    Set<APIStore> updateApiStores = new HashSet<APIStore>();
    Set<APIStore> removedApiStores = new HashSet<APIStore>();
    StringBuilder errorStatus = new StringBuilder("Failed to update External Stores : ");
    boolean failure = false;
    if (publishedStores != null) {
        removedApiStores.addAll(publishedStores);
        removedApiStores.removeAll(apiStoreSet);
    }
    for (APIStore apiStore : apiStoreSet) {
        boolean publishedToStore = false;
        if (publishedStores != null) {
            for (APIStore store : publishedStores) {
                // If selected external store in edit page is already saved in db
                if (store.equals(apiStore)) {
                    // Check if there's a modification happened in config file external store definition
                    try {
                        if (!isAPIAvailableInExternalAPIStore(api, apiStore)) {
                            // API is not available
                            continue;
                        }
                    } catch (APIManagementException e) {
                        failure = true;
                        log.error(e);
                        errorStatus.append(store.getDisplayName()).append(',');
                    }
                    // Already the API has published to external APIStore
                    publishedToStore = true;
                    // In this case,the API is already added to external APIStore,thus we don't need to publish it again.
                    // We need to update the API in external Store.
                    // Include to update API in external APIStore
                    updateApiStores.add(APIUtil.getExternalAPIStore(store.getName(), tenantId));
                }
            }
        }
        if (!publishedToStore) {
            // If the API has not yet published to selected external APIStore
            notPublishedAPIStores.add(APIUtil.getExternalAPIStore(apiStore.getName(), tenantId));
        }
    }
    // Publish API to external APIStore which are not yet published
    try {
        publishToExternalAPIStores(api, notPublishedAPIStores, apiOlderVersionExist);
    } catch (APIManagementException e) {
        handleException("Failed to publish API to external Store. ", e);
    }
    // Update the APIs which are already exist in the external APIStore
    updateAPIInExternalAPIStores(api, updateApiStores);
    // Update database saved published APIStore details
    updateExternalAPIStoresDetails(api.getUuid(), updateApiStores);
    deleteFromExternalAPIStores(api, removedApiStores);
    if (failure) {
        throw new APIManagementException(errorStatus.substring(0, errorStatus.length() - 2));
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIStore(org.wso2.carbon.apimgt.api.model.APIStore) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 100 with Subscription

use of org.wso2.carbon.apimgt.api.model.webhooks.Subscription in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeSubscription.

/**
 * Removes a subscription specified by SubscribedAPI object
 *
 * @param subscription SubscribedAPI object
 * @param organization Organization
 * @throws APIManagementException
 */
@Override
public void removeSubscription(SubscribedAPI subscription, String organization) throws APIManagementException {
    String uuid = subscription.getUUID();
    if (subscription != null) {
        Application application = subscription.getApplication();
        Identifier identifier = subscription.getApiId() != null ? subscription.getApiId() : subscription.getProductId();
        String userId = application.getSubscriber().getName();
        removeSubscription(identifier, userId, application.getId(), organization);
        if (log.isDebugEnabled()) {
            String appName = application.getName();
            String logMessage = "Identifier:  " + identifier.toString() + " subscription (uuid : " + uuid + ") removed from app " + appName;
            log.debug(logMessage);
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(application.getId()), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
    } else {
        throw new APIManagementException(String.format("Subscription for UUID:%s does not exist.", subscription.getUUID()));
    }
}
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) 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) Application(org.wso2.carbon.apimgt.api.model.Application)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 ArrayList (java.util.ArrayList)69 Test (org.testng.annotations.Test)58 Subscription (org.wso2.carbon.apimgt.core.models.Subscription)58 Test (org.junit.Test)56 SQLException (java.sql.SQLException)55 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)51 Connection (java.sql.Connection)49 PreparedStatement (java.sql.PreparedStatement)48 ResultSet (java.sql.ResultSet)39 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)37 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)35 APISubscriptionDAO (org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO)34 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)34 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)31 Application (org.wso2.carbon.apimgt.core.models.Application)30 API (org.wso2.carbon.apimgt.core.models.API)28 Response (javax.ws.rs.core.Response)24 Application (org.wso2.carbon.apimgt.api.model.Application)22 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)22