Search in sources :

Example 1 with SubscriptionBlockedException

use of org.wso2.carbon.apimgt.api.SubscriptionBlockedException in project carbon-apimgt by wso2.

the class ApiMgtDAO method addSubscription.

private int addSubscription(Connection connection, ApiTypeWrapper apiTypeWrapper, Application application, String subscriptionStatus, String subscriber) throws APIManagementException, SQLException {
    final boolean isProduct = apiTypeWrapper.isAPIProduct();
    int subscriptionId = -1;
    int id = -1;
    String apiUUID;
    Identifier identifier;
    String tier;
    // Query to check if this subscription already exists
    String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_API_SQL;
    if (!isProduct) {
        identifier = apiTypeWrapper.getApi().getId();
        apiUUID = apiTypeWrapper.getApi().getUuid();
        if (apiUUID != null) {
            id = getAPIID(apiUUID);
        }
        if (id == -1) {
            id = identifier.getId();
        }
    } else {
        identifier = apiTypeWrapper.getApiProduct().getId();
        id = apiTypeWrapper.getApiProduct().getProductId();
        apiUUID = apiTypeWrapper.getApiProduct().getUuid();
    }
    int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
    try (PreparedStatement ps = connection.prepareStatement(checkDuplicateQuery)) {
        ps.setInt(1, id);
        ps.setInt(2, application.getId());
        try (ResultSet resultSet = ps.executeQuery()) {
            // If the subscription already exists
            if (resultSet.next()) {
                String subStatus = resultSet.getString("SUB_STATUS");
                String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
                if ((APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.ON_HOLD.equals(subStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) && APIConstants.SubscriptionCreatedStatus.SUBSCRIBE.equals(subCreationStatus)) {
                    // Throw error saying subscription already exists.
                    log.error(String.format("Subscription already exists for API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
                    throw new SubscriptionAlreadyExistingException(String.format("Subscription already exists for" + " API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
                } else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
                    deleteSubscriptionByApiIDAndAppID(id, application.getId(), connection);
                } else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
                    log.error(String.format(String.format("Subscription to API/API Prouct %%s through application" + " %%s was blocked"), apiTypeWrapper.getName(), application.getName()));
                    throw new SubscriptionBlockedException(String.format("Subscription to API/API Product %s " + "through application %s was blocked", apiTypeWrapper.getName(), application.getName()));
                } else if (APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) {
                    throw new SubscriptionBlockedException("Subscription to API " + apiTypeWrapper.getName() + " through application " + application.getName() + " was rejected");
                }
            }
        }
    }
    // This query to update the AM_SUBSCRIPTION table
    String sqlQuery = SQLConstants.ADD_SUBSCRIPTION_SQL;
    // Adding data to the AM_SUBSCRIPTION table
    // ps = conn.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
    String subscriptionIDColumn = "SUBSCRIPTION_ID";
    String subscriptionUUID = UUID.randomUUID().toString();
    if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
        subscriptionIDColumn = "subscription_id";
    }
    try (PreparedStatement preparedStForInsert = connection.prepareStatement(sqlQuery, new String[] { subscriptionIDColumn })) {
        if (!isProduct) {
            tier = apiTypeWrapper.getApi().getId().getTier();
            preparedStForInsert.setString(1, tier);
            preparedStForInsert.setString(10, tier);
        } else {
            tier = apiTypeWrapper.getApiProduct().getId().getTier();
            preparedStForInsert.setString(1, tier);
            preparedStForInsert.setString(10, tier);
        }
        preparedStForInsert.setInt(2, id);
        preparedStForInsert.setInt(3, application.getId());
        preparedStForInsert.setString(4, subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED);
        preparedStForInsert.setString(5, APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
        preparedStForInsert.setString(6, subscriber);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        preparedStForInsert.setTimestamp(7, timestamp);
        preparedStForInsert.setTimestamp(8, timestamp);
        preparedStForInsert.setString(9, subscriptionUUID);
        preparedStForInsert.executeUpdate();
        try (ResultSet rs = preparedStForInsert.getGeneratedKeys()) {
            while (rs.next()) {
                // subscriptionId = rs.getInt(1);
                subscriptionId = Integer.parseInt(rs.getString(1));
            }
        }
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
    SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, subscriptionUUID, id, apiUUID, application.getId(), application.getUUID(), tier, (subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED));
    return subscriptionId;
}
Also used : SubscriptionBlockedException(org.wso2.carbon.apimgt.api.SubscriptionBlockedException) SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) ResultSet(java.sql.ResultSet) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 2 with SubscriptionBlockedException

use of org.wso2.carbon.apimgt.api.SubscriptionBlockedException in project carbon-apimgt by wso2.

the class ApiMgtDAO method makeKeysForwardCompatible.

public void makeKeysForwardCompatible(ApiTypeWrapper apiTypeWrapper, List<API> oldAPIVersions) throws APIManagementException {
    // if there are no previous versions, there is no need to copy subscriptions
    if (oldAPIVersions == null || oldAPIVersions.isEmpty()) {
        return;
    }
    String getSubscriptionDataQuery = SQLConstants.GET_SUBSCRIPTION_DATA_SQL.replaceAll("_API_VERSION_LIST_", String.join(",", Collections.nCopies(oldAPIVersions.size(), "?")));
    APIIdentifier apiIdentifier = apiTypeWrapper.getApi().getId();
    try {
        // Retrieve all the existing subscription for the old version
        try (Connection connection = APIMgtDBUtil.getConnection()) {
            connection.setAutoCommit(false);
            try (PreparedStatement prepStmt = connection.prepareStatement(getSubscriptionDataQuery)) {
                prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
                prepStmt.setString(2, apiIdentifier.getApiName());
                int index = 3;
                for (API oldAPI : oldAPIVersions) {
                    prepStmt.setString(index++, oldAPI.getId().getVersion());
                }
                try (ResultSet rs = prepStmt.executeQuery()) {
                    List<SubscriptionInfo> subscriptionData = new ArrayList<SubscriptionInfo>();
                    while (rs.next() && !(APIConstants.SubscriptionStatus.ON_HOLD.equals(rs.getString("SUB_STATUS")))) {
                        int subscriptionId = rs.getInt("SUBSCRIPTION_ID");
                        String tierId = rs.getString("TIER_ID");
                        int applicationId = rs.getInt("APPLICATION_ID");
                        String apiVersion = rs.getString("VERSION");
                        String subscriptionStatus = rs.getString("SUB_STATUS");
                        SubscriptionInfo info = new SubscriptionInfo(subscriptionId, tierId, applicationId, apiVersion, subscriptionStatus);
                        subscriptionData.add(info);
                    }
                    // To keep track of already added subscriptions (apps)
                    List<Integer> addedApplications = new ArrayList<>();
                    for (int i = oldAPIVersions.size() - 1; i >= 0; i--) {
                        API oldAPI = oldAPIVersions.get(i);
                        for (SubscriptionInfo info : subscriptionData) {
                            try {
                                if (info.getApiVersion().equals(oldAPI.getId().getVersion()) && !addedApplications.contains(info.getApplicationId())) {
                                    String subscriptionStatus;
                                    if (APIConstants.SubscriptionStatus.BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.BLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.UNBLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.UNBLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.REJECTED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                                    } else {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.ON_HOLD;
                                    }
                                    apiTypeWrapper.setTier(info.getTierId());
                                    Application application = getLightweightApplicationById(connection, info.getApplicationId());
                                    int subscriptionId = addSubscription(connection, apiTypeWrapper, application, subscriptionStatus, apiIdentifier.getProviderName());
                                    if (subscriptionId == -1) {
                                        String msg = "Unable to add a new subscription for the API: " + apiIdentifier.getName() + ":v" + apiIdentifier.getVersion();
                                        log.error(msg);
                                        throw new APIManagementException(msg);
                                    }
                                    addedApplications.add(info.getApplicationId());
                                }
                            // catching the exception because when copy the api without the option "require
                            // re-subscription"
                            // need to go forward rather throwing the exception
                            } catch (SubscriptionAlreadyExistingException e) {
                                log.error("Error while adding subscription " + e.getMessage(), e);
                            } catch (SubscriptionBlockedException e) {
                                log.info("Subscription is blocked: " + e.getMessage());
                            }
                        }
                    }
                }
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    } catch (SQLException e) {
        handleException("Error when executing the SQL queries", e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) SubscriptionBlockedException(org.wso2.carbon.apimgt.api.SubscriptionBlockedException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResultSet(java.sql.ResultSet) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) Application(org.wso2.carbon.apimgt.api.model.Application)

Aggregations

PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SubscriptionAlreadyExistingException (org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException)2 SubscriptionBlockedException (org.wso2.carbon.apimgt.api.SubscriptionBlockedException)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 Timestamp (java.sql.Timestamp)1 ArrayList (java.util.ArrayList)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 API (org.wso2.carbon.apimgt.api.model.API)1 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)1 Application (org.wso2.carbon.apimgt.api.model.Application)1 Identifier (org.wso2.carbon.apimgt.api.model.Identifier)1 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)1 SubscriptionEvent (org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent)1