Search in sources :

Example 61 with Subscriber

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

the class ApiMgtDAO method isApplicationExist.

/**
 * Check whether given application name is available under current subscriber or group
 *
 * @param appName  application name
 * @param username subscriber
 * @param groupId  group of the subscriber
 * @param organization identifier of the organization
 * @return true if application is available for the subscriber
 * @throws APIManagementException if failed to get applications for given subscriber
 */
public boolean isApplicationExist(String appName, String username, String groupId, String organization) throws APIManagementException {
    if (username == null) {
        return false;
    }
    Subscriber subscriber = getSubscriber(username);
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    int appId = 0;
    String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX;
    String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
    String whereClauseWithGroupIdCaseInsensitive = " AND (APP.GROUP_ID = ? " + "OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) 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 = ? ) " + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_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(?))" + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
    String whereClause = " AND SUB.USER_ID = ? ";
    String whereClauseCaseInsensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
    try {
        connection = APIMgtDBUtil.getConnection();
        if (!StringUtils.isEmpty(groupId)) {
            if (multiGroupAppSharingEnabled) {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithMultiGroupId;
                }
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] grpIdArray = groupId.split(",");
                int noOfParams = grpIdArray.length;
                preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 3);
                preparedStatement.setString(1, appName);
                preparedStatement.setString(2, organization);
                int paramIndex = noOfParams + 2;
                preparedStatement.setString(++paramIndex, tenantDomain);
                preparedStatement.setString(++paramIndex, subscriber.getName());
                preparedStatement.setString(++paramIndex, tenantDomain + '/' + groupId);
            } else {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithGroupId;
                }
                preparedStatement = connection.prepareStatement(sqlQuery);
                preparedStatement.setString(1, appName);
                preparedStatement.setString(2, organization);
                preparedStatement.setString(3, groupId);
                preparedStatement.setString(4, subscriber.getName());
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                sqlQuery += whereClauseCaseInsensitive;
            } else {
                sqlQuery += whereClause;
            }
            preparedStatement = connection.prepareStatement(sqlQuery);
            preparedStatement.setString(1, appName);
            preparedStatement.setString(2, organization);
            preparedStatement.setString(3, subscriber.getName());
        }
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            appId = resultSet.getInt("APPLICATION_ID");
        }
        if (appId > 0) {
            return true;
        }
    } catch (SQLException e) {
        handleException("Error while getting the id  of " + appName + " from the persistence store.", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return false;
}
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)

Example 62 with Subscriber

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

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

the class ApiMgtDAO method removeAPIRating.

/**
 * @param uuid API uuid
 * @param userId     User Id
 * @throws APIManagementException if failed to remove API user Rating
 */
public void removeAPIRating(String uuid, String userId, Connection conn) throws APIManagementException, SQLException {
    PreparedStatement ps = null;
    PreparedStatement psSelect = null;
    ResultSet rs = null;
    try {
        int tenantId;
        String rateId = null;
        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 check the ratings already exists for the user in the AM_API_RATINGS table
        String sqlQuery = SQLConstants.GET_API_RATING_ID_SQL;
        psSelect = conn.prepareStatement(sqlQuery);
        psSelect.setInt(1, id);
        psSelect.setInt(2, subscriber.getId());
        rs = psSelect.executeQuery();
        while (rs.next()) {
            rateId = rs.getString("RATING_ID");
        }
        String sqlDeleteQuery;
        if (rateId != null) {
            // This query to delete the specific rate row from the AM_API_RATINGS table
            sqlDeleteQuery = SQLConstants.REMOVE_RATING_SQL;
            // Adding data to the AM_API_RATINGS  table
            ps = conn.prepareStatement(sqlDeleteQuery);
            ps.setString(1, rateId);
            ps.executeUpdate();
        }
    } catch (SQLException e) {
        handleException("Failed to delete API rating", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, null, null);
        APIMgtDBUtil.closeAllConnections(psSelect, null, rs);
    }
}
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)

Example 64 with Subscriber

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

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

the class ApiMgtDAO method isApplicationGroupCombinationExists.

/**
 * @param applicationName application name
 * @param username username
 * @param groupId group id
 * @return whether a certain application group combination exists or not
 * @throws APIManagementException if failed to assess whether a certain application group combination exists or not
 */
public boolean isApplicationGroupCombinationExists(String applicationName, String username, String groupId) throws APIManagementException {
    if (username == null) {
        return false;
    }
    Subscriber subscriber = getSubscriber(username);
    int appId = 0;
    String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX_FOR_GROUP_COMPARISON;
    String whereClauseWithGroupId = " AND APP.GROUP_ID = ?";
    String whereClauseWithMultiGroupId = " AND (APP.APPLICATION_ID IN (SELECT APPLICATION_ID  FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?))";
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        if (!StringUtils.isEmpty(groupId)) {
            if (multiGroupAppSharingEnabled) {
                sqlQuery += whereClauseWithMultiGroupId;
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] grpIdArray = groupId.split(",");
                int noOfParams = grpIdArray.length;
                try (PreparedStatement preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 2)) {
                    preparedStatement.setString(1, applicationName);
                    int paramIndex = noOfParams + 1;
                    preparedStatement.setString(++paramIndex, tenantDomain);
                    try (ResultSet resultSet = preparedStatement.executeQuery()) {
                        if (resultSet.next()) {
                            appId = resultSet.getInt("APPLICATION_ID");
                        }
                        if (appId > 0) {
                            return true;
                        }
                    }
                }
            } else {
                sqlQuery += whereClauseWithGroupId;
                try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
                    preparedStatement.setString(1, applicationName);
                    preparedStatement.setString(2, groupId);
                    try (ResultSet resultSet = preparedStatement.executeQuery()) {
                        if (resultSet.next()) {
                            appId = resultSet.getInt("APPLICATION_ID");
                        }
                        if (appId > 0) {
                            return true;
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        handleException("Error while getting application group combination data for application: " + applicationName, e);
    }
    return false;
}
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)

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