Search in sources :

Example 56 with Subscriber

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

the class ImportUtils method importSubscriptions.

/**
 * Import and add subscriptions of a particular application for the available APIs and API products
 *
 * @param subscribedAPIs Subscribed APIs
 * @param userId         Username of the subscriber
 * @param application    Application
 * @param update         Whether to update the application or not
 * @param apiConsumer    API Consumer
 * @param organization   Organization
 * @return a list of APIIdentifiers of the skipped subscriptions
 * @throws APIManagementException if an error occurs while importing and adding subscriptions
 * @throws UserStoreException     if an error occurs while checking whether the tenant domain exists
 */
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
    List<APIIdentifier> skippedAPIList = new ArrayList<>();
    for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
        APIIdentifier apiIdentifier = subscribedAPI.getApiId();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
        if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
            String name = apiIdentifier.getApiName();
            String version = apiIdentifier.getVersion();
            // Creating a solr compatible search query, here we will execute a search query without wildcard *s
            StringBuilder searchQuery = new StringBuilder();
            String[] searchCriteria = { name, "version:" + version };
            for (int i = 0; i < searchCriteria.length; i++) {
                if (i == 0) {
                    searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
                } else {
                    searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
                }
            }
            Map matchedAPIs;
            matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
            Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
            if (apiSet != null && !apiSet.isEmpty()) {
                Object type = apiSet.iterator().next();
                ApiTypeWrapper apiTypeWrapper = null;
                String apiOrApiProductUuid;
                // Check whether the object is ApiProduct
                if (isApiProduct(type)) {
                    APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
                    apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
                } else {
                    API api = (API) apiSet.iterator().next();
                    apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
                }
                apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
                // Tier of the imported subscription
                String targetTier = subscribedAPI.getThrottlingPolicy();
                // Checking whether the target tier is available
                if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
                    apiTypeWrapper.setTier(targetTier);
                    // It will throw an error if subscriber already exists
                    if (update == null || !update) {
                        apiConsumer.addSubscription(apiTypeWrapper, userId, application);
                    } else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
                        // on update skip subscriptions that already exists
                        apiConsumer.addSubscription(apiTypeWrapper, userId, application);
                    }
                } else {
                    log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
                    skippedAPIList.add(subscribedAPI.getApiId());
                }
            } else {
                log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
                skippedAPIList.add(subscribedAPI.getApiId());
            }
        } else {
            log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
            skippedAPIList.add(subscribedAPI.getApiId());
        }
    }
    return skippedAPIList;
}
Also used : ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) Set(java.util.Set) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONObject(org.json.simple.JSONObject) API(org.wso2.carbon.apimgt.api.model.API) ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) Map(java.util.Map)

Example 57 with Subscriber

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

the class SubscriberRegistrationInterceptor method handleMessage.

/**
 * Handles the incoming message after post authentication. Only used in Store REST API, to register a newly
 * signed up store user who hasn't logged in to Store for the first time either via REST API or Store UI.
 * This method will register the user as a subscriber
 * (register in AM_SUBSCRIBER table, add the default application for subscriber etc.).
 *
 * @param message cxf message
 */
@Override
@MethodStats
public void handleMessage(Message message) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    // by-passes the interceptor if user is an annonymous user
    if (username.equalsIgnoreCase(APIConstants.WSO2_ANONYMOUS_USER)) {
        return;
    }
    // checking if the subscriber exists in the subscriber cache
    Cache<String, Subscriber> subscriberCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.API_SUBSCRIBER_CACHE);
    if (subscriberCache.get(username) != null) {
        return;
    }
    // check the existence in the database
    String groupId = RestApiUtil.getLoggedInUserGroupId();
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    try {
        // takes a consumer object using the user set in thread local carbon context
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        Subscriber subscriber = apiConsumer.getSubscriber(username);
        if (subscriber == null) {
            synchronized ((username + LOCK_POSTFIX).intern()) {
                subscriber = apiConsumer.getSubscriber(username);
                if (subscriber == null) {
                    message.getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
                    if (!hasSubscribeScope(message)) {
                        // permission. It should be allowed.
                        if (logger.isDebugEnabled()) {
                            logger.debug("User " + username + " does not have subscribe scope " + "(" + APIM_SUBSCRIBE_SCOPE + ")");
                        }
                        return;
                    }
                    if (!APIConstants.SUPER_TENANT_DOMAIN.equalsIgnoreCase(tenantDomain)) {
                        loadTenantRegistry();
                    }
                    apiConsumer.addSubscriber(username, groupId);
                    // The subscriber object added here is not a complete subscriber object. It will only contain
                    // username
                    subscriberCache.put(username, new Subscriber(username));
                    if (logger.isDebugEnabled()) {
                        logger.debug("Subscriber " + username + " added to AM_SUBSCRIBER database");
                    }
                }
            }
        } else {
            subscriberCache.put(username, subscriber);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Unable to add the subscriber " + username, e, logger);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 58 with Subscriber

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

the class ThrottleConditionEvaluatorTest method testApplicabilityOfMatchingJWTClaimsCondition.

@Test
public void testApplicabilityOfMatchingJWTClaimsCondition() {
    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("JWTClaimsConditionGroup");
    ConditionDTO matchingCondition = new ConditionDTO();
    matchingCondition.setConditionType("JWTClaims");
    matchingCondition.setConditionName("http://wso2.org/claims/subscriber");
    matchingCondition.setConditionValue("admin");
    ConditionDTO[] conditionDTOS = { matchingCondition };
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = { conditionGroupDTO };
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(JWTToken);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions(messageContext, authenticationContext, conditionGroupDTOS);
    Assert.assertEquals(matchingConditionGroups.get(0).getConditionGroupId(), "JWTClaimsConditionGroup");
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Example 59 with Subscriber

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

the class ThrottleConditionEvaluatorTest method testApplicabilityOfInvertedJWTClaimsCondition.

@Test
public void testApplicabilityOfInvertedJWTClaimsCondition() {
    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("JWTClaimsConditionGroup");
    ConditionDTO invertedCondition = new ConditionDTO();
    invertedCondition.setConditionType("JWTClaims");
    invertedCondition.setConditionName("http://wso2.org/claims/subscriber");
    invertedCondition.setConditionValue("admin");
    invertedCondition.isInverted(true);
    ConditionDTO[] conditionDTOS = { invertedCondition };
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = { conditionGroupDTO };
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(JWTToken);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions(messageContext, authenticationContext, conditionGroupDTOS);
    Assert.assertNull(matchingConditionGroups.get(0));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Example 60 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