Search in sources :

Example 21 with Subscriber

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

the class ApiMgtDAO method getSubscribedAPIs.

/**
 * This method returns the set of APIs for given subscriber, subscribed under the specified application.
 *
 * @param subscriber      subscriber
 * @param applicationName Application Name
 * @return Set<API>
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
 */
public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String applicationName, String groupingId) throws APIManagementException {
    Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_SQL;
    String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
    String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?" + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
    String whereClause = " AND SUB.USER_ID = ? ";
    String whereClauseCaseSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
    String whereClauseWithMultiGroupId = " AND  ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params)  AND TENANT = ?))  OR  ( SUB.USER_ID = ? ))";
    String whereClauseWithMultiGroupIdCaseInsensitive = " AND  ( (APP.APPLICATION_ID IN  (SELECT APPLICATION_ID " + "FROM AM_APPLICATION_GROUP_MAPPING  WHERE GROUP_ID IN ($params) AND TENANT = ?))  OR  ( LOWER(SUB" + ".USER_ID) = LOWER" + "(?) ))";
    try {
        connection = APIMgtDBUtil.getConnection();
        if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
            if (multiGroupAppSharingEnabled) {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithMultiGroupId;
                }
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] groupIdArr = groupingId.split(",");
                ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                int paramIndex = groupIdArr.length + 2;
                ps.setString(++paramIndex, tenantDomain);
                ps.setString(++paramIndex, subscriber.getName());
            } else {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
                } else {
                    sqlQuery += whereClauseWithGroupId;
                }
                ps = connection.prepareStatement(sqlQuery);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                ps.setString(3, groupingId);
                ps.setString(4, subscriber.getName());
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                sqlQuery += whereClauseCaseSensitive;
            } else {
                sqlQuery += whereClause;
            }
            ps = connection.prepareStatement(sqlQuery);
            int tenantId = APIUtil.getTenantId(subscriber.getName());
            ps.setInt(1, tenantId);
            ps.setString(2, applicationName);
            ps.setString(3, subscriber.getName());
        }
        result = ps.executeQuery();
        while (result.next()) {
            APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
            apiIdentifier.setUuid(result.getString("API_UUID"));
            SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
            subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
            subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
            subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
            subscribedAPI.setUUID(result.getString("SUB_UUID"));
            subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
            Application application = new Application(result.getString("APP_NAME"), subscriber);
            application.setUUID(result.getString("APP_UUID"));
            subscribedAPI.setApplication(application);
            subscribedAPIs.add(subscribedAPI);
        }
    } catch (SQLException e) {
        handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
    return subscribedAPIs;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 22 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber 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 23 with Subscriber

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

the class ApiMgtDAO method getSubscriber.

public Subscriber getSubscriber(int subscriberId) throws APIManagementException {
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        String query = SQLConstants.GET_SUBSCRIBER_SQL;
        ps = conn.prepareStatement(query);
        ps.setInt(1, subscriberId);
        rs = ps.executeQuery();
        if (rs.next()) {
            Subscriber subscriber = new Subscriber(rs.getString("USER_ID"));
            subscriber.setId(subscriberId);
            subscriber.setTenantId(rs.getInt("TENANT_ID"));
            subscriber.setEmail(rs.getString("EMAIL_ADDRESS"));
            subscriber.setSubscribedDate(new java.util.Date(rs.getTimestamp("DATE_SUBSCRIBED").getTime()));
            return subscriber;
        }
    } catch (SQLException e) {
        handleException("Error while retrieving subscriber: " + e.getMessage(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return null;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) Date(java.util.Date) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 24 with Subscriber

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

the class ApiMgtDAO method getApplicationByName.

/**
 * Fetches an Application by name.
 *
 * @param applicationName Name of the Application
 * @param userId          Name of the User.
 * @param groupId         Group ID
 * @throws APIManagementException
 */
public Application getApplicationByName(String applicationName, String userId, String groupId) throws APIManagementException {
    // mysql> select APP.APPLICATION_ID, APP.NAME, APP.SUBSCRIBER_ID,APP.APPLICATION_TIER,APP.CALLBACK_URL,APP
    // .DESCRIPTION,
    // APP.APPLICATION_STATUS from AM_SUBSCRIBER as SUB,AM_APPLICATION as APP
    // where SUB.user_id='admin' AND APP.name='DefaultApplication' AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID;
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    int applicationId = 0;
    Application application = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        String query = SQLConstants.GET_APPLICATION_BY_NAME_PREFIX;
        String whereClause = "  WHERE SUB.USER_ID =? AND APP.NAME=? AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
        String whereClauseCaseInSensitive = "  WHERE LOWER(SUB.USER_ID) =LOWER(?) AND APP.NAME=? AND SUB" + "" + ".SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
        String whereClauseWithGroupId = "  WHERE  (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?)) AND " + "APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithGroupIdCaseInSensitive = "  WHERE  (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND LOWER(SUB.USER_ID) = LOWER(?))) AND " + "APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithMultiGroupId = "  WHERE  ((APP.APPLICATION_ID IN (SELECT APPLICATION_ID  FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?))  OR   SUB.USER_ID = ? " + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?))) " + "AND APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithMultiGroupIdCaseInSensitive = "  WHERE  ((APP.APPLICATION_ID IN (SELECT APPLICATION_ID  FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?))  " + "OR   LOWER(SUB.USER_ID) = LOWER(?)  " + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = " + "?))) " + "AND APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        if (groupId != null && !"null".equals(groupId) && !groupId.isEmpty()) {
            if (multiGroupAppSharingEnabled) {
                Subscriber subscriber = getSubscriber(userId);
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                if (forceCaseInsensitiveComparisons) {
                    query = query + whereClauseWithMultiGroupIdCaseInSensitive;
                } else {
                    query = query + whereClauseWithMultiGroupId;
                }
                String[] groupIds = groupId.split(",");
                int parameterIndex = groupIds.length;
                prepStmt = fillQueryParams(connection, query, groupIds, 1);
                prepStmt.setString(++parameterIndex, tenantDomain);
                prepStmt.setString(++parameterIndex, userId);
                prepStmt.setString(++parameterIndex, tenantDomain + '/' + groupId);
                prepStmt.setString(++parameterIndex, applicationName);
            } else {
                if (forceCaseInsensitiveComparisons) {
                    query = query + whereClauseWithGroupIdCaseInSensitive;
                } else {
                    query = query + whereClauseWithGroupId;
                }
                prepStmt = connection.prepareStatement(query);
                prepStmt.setString(1, groupId);
                prepStmt.setString(2, userId);
                prepStmt.setString(3, applicationName);
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                query = query + whereClauseCaseInSensitive;
            } else {
                query = query + whereClause;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, userId);
            prepStmt.setString(2, applicationName);
        }
        rs = prepStmt.executeQuery();
        while (rs.next()) {
            String subscriberId = rs.getString("SUBSCRIBER_ID");
            String subscriberName = rs.getString("USER_ID");
            Subscriber subscriber = new Subscriber(subscriberName);
            subscriber.setId(Integer.parseInt(subscriberId));
            application = new Application(applicationName, subscriber);
            application.setOwner(rs.getString("CREATED_BY"));
            application.setDescription(rs.getString("DESCRIPTION"));
            application.setStatus(rs.getString("APPLICATION_STATUS"));
            application.setCallbackUrl(rs.getString("CALLBACK_URL"));
            applicationId = rs.getInt("APPLICATION_ID");
            application.setId(applicationId);
            application.setTier(rs.getString("APPLICATION_TIER"));
            application.setUUID(rs.getString("UUID"));
            application.setGroupId(rs.getString("GROUP_ID"));
            application.setOwner(rs.getString("CREATED_BY"));
            application.setTokenType(rs.getString("TOKEN_TYPE"));
            if (multiGroupAppSharingEnabled) {
                setGroupIdInApplication(connection, application);
            }
            if (application != null) {
                Map<String, String> applicationAttributes = getApplicationAttributes(connection, applicationId);
                application.setApplicationAttributes(applicationAttributes);
            }
        }
    } catch (SQLException e) {
        handleException("Error while obtaining details of the Application : " + applicationName, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return application;
}
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) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 25 with Subscriber

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

the class ApiMgtDAO method getUserRating.

/**
 * @param uuid API uuid
 * @param userId     User Id
 * @throws APIManagementException if failed to get User API Rating
 */
public int getUserRating(String uuid, String userId, Connection conn) throws APIManagementException, SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    int userRating = 0;
    try {
        int tenantId;
        tenantId = APIUtil.getTenantId(userId);
        // Get subscriber Id
        Subscriber subscriber = getSubscriber(userId, tenantId, conn);
        if (subscriber == null) {
            String msg = "Could not load Subscriber records for: " + userId;
            log.error(msg);
            throw new APIManagementException(msg);
        }
        // Get API Id
        int id = -1;
        id = getAPIID(uuid, conn);
        if (id == -1) {
            String msg = "Could not load API record for API with UUID : " + uuid;
            log.error(msg);
            throw new APIManagementException(msg);
        }
        // This query to update the AM_API_RATINGS table
        String sqlQuery = SQLConstants.GET_API_RATING_SQL;
        // Adding data to the AM_API_RATINGS  table
        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, id);
        ps.setInt(2, subscriber.getId());
        rs = ps.executeQuery();
        while (rs.next()) {
            userRating = rs.getInt("RATING");
        }
    } catch (SQLException e) {
        handleException("Failed to add Application", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, null, rs);
    }
    return userRating;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)98 Test (org.junit.Test)64 Application (org.wso2.carbon.apimgt.api.model.Application)63 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)60 PreparedStatement (java.sql.PreparedStatement)39 SQLException (java.sql.SQLException)39 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 ResultSet (java.sql.ResultSet)37 Connection (java.sql.Connection)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 Tier (org.wso2.carbon.apimgt.api.model.Tier)20 ArrayList (java.util.ArrayList)19 HashSet (java.util.HashSet)19 Date (java.util.Date)14 HashMap (java.util.HashMap)11 LinkedHashSet (java.util.LinkedHashSet)10 JSONObject (org.json.simple.JSONObject)10 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)10 TreeMap (java.util.TreeMap)9