Search in sources :

Example 21 with SubscribedAPI

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

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCacheExpiredTokenTenant.

@Test
public void testAuthenticateNoCacheExpiredTokenTenant() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("abc.com");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    Mockito.when(invalidCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    PowerMockito.when(GatewayUtils.verifyTokenSignature(Mockito.any(SignedJWT.class), Mockito.anyString())).thenReturn(true);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(true);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.doNothing().when(PrivilegedCarbonContext.class, "startTenantFlow");
    PowerMockito.doNothing().when(privilegedCarbonContext).setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertFalse(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    Assert.assertEquals(authenticate.getErrorMessage(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    Mockito.verify(internalKeyCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(invalidCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(internalKeyCache, Mockito.times(0)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "abc.com");
    Mockito.verify(invalidCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "abc.com");
    Mockito.verify(internalKeyDataCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.any(AuthenticationContext.class));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 22 with SubscribedAPI

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

the class APIConsumerImpl method getLightWeightSubscribedIdentifiers.

@Override
public Set<SubscribedAPI> getLightWeightSubscribedIdentifiers(String organization, Subscriber subscriber, APIIdentifier apiIdentifier, String groupingId) throws APIManagementException {
    Set<SubscribedAPI> subscribedAPISet = new HashSet<SubscribedAPI>();
    Set<SubscribedAPI> subscribedAPIs = getLightWeightSubscribedAPIs(organization, subscriber, groupingId);
    for (SubscribedAPI api : subscribedAPIs) {
        if (api.getApiId().equals(apiIdentifier)) {
            subscribedAPISet.add(api);
        }
    }
    return subscribedAPISet;
}
Also used : SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 23 with SubscribedAPI

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

the class APIConsumerImpl method updateSubscription.

@Override
public SubscriptionResponse updateSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application, String inputSubscriptionId, String currentThrottlingPolicy, String requestedThrottlingPolicy) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUId;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        apiId = product.getProductId();
        apiUUId = product.getUuid();
        identifier = product.getId();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = identifier.getId();
        apiUUId = api.getUuid();
        apiContext = api.getContext();
    }
    checkSubscriptionAllowed(apiTypeWrapper);
    WorkflowResponse workflowResponse = null;
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state)) {
        subscriptionId = apiMgtDAO.updateSubscription(apiTypeWrapper, inputSubscriptionId, APIConstants.SubscriptionStatus.TIER_UPDATE_PENDING, requestedThrottlingPolicy);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        try {
            WorkflowExecutor updateSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(updateSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            workflowDTO.setCallbackUrl(updateSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(requestedThrottlingPolicy);
            workflowDTO.setApplicationName(application.getName());
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI updatedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = updatedSubscription.getSubStatus();
            subscriptionUUID = updatedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, application.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            subsLogObject.put(APIConstants.AuditLogConstants.REQUESTED_TIER, requestedThrottlingPolicy);
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
        // 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_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + application.getName();
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
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) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) 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) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 24 with SubscribedAPI

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

the class APIConsumerImpl method addSubscription.

@Override
public SubscriptionResponse addSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUID;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        identifier = product.getId();
        apiId = product.getProductId();
        apiUUID = product.getUuid();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = api.getId().getId();
        apiUUID = api.getUuid();
        apiContext = api.getContext();
    }
    WorkflowResponse workflowResponse = null;
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
    checkSubscriptionAllowed(apiTypeWrapper);
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state) || APIConstants.PROTOTYPED.equals(state)) {
        subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, tenantAwareUsername);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        String applicationName = application.getName();
        try {
            WorkflowExecutor addSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(identifier.getTier());
            workflowDTO.setApplicationName(applicationName);
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            // If the workflow execution fails, roll back transaction by removing the subscription entry.
            apiMgtDAO.removeSubscriptionById(subscriptionId);
            log.error("Could not execute Workflow", e);
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = addedSubscription.getSubStatus();
            subscriptionUUID = addedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        // only send the notification if approved
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + applicationName;
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
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) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) 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) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 25 with SubscribedAPI

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

the class APIMgtDAOTest method testForwardingBlockedAndProdOnlyBlockedSubscriptionsToNewAPIVersion.

@Test
public void testForwardingBlockedAndProdOnlyBlockedSubscriptionsToNewAPIVersion() throws APIManagementException {
    List<API> oldApiVersionList = new ArrayList<>();
    Subscriber subscriber = new Subscriber("new_sub_user1");
    subscriber.setEmail("newuser1@wso2.com");
    subscriber.setSubscribedDate(new Date());
    subscriber.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    apiMgtDAO.addSubscriber(subscriber, null);
    Application application = new Application("SUB_FORWARD_APP", subscriber);
    int applicationId = apiMgtDAO.addApplication(application, subscriber.getName(), "org1");
    // Add the first version of the API
    APIIdentifier apiId1 = new APIIdentifier("subForwardProvider", "SubForwardTestAPI", "V1.0.0");
    apiId1.setTier("T20");
    API api = new API(apiId1);
    api.setContext("/subForward");
    api.setContextTemplate("/subForward/{version}");
    api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
    api.getId().setId(apiMgtDAO.addAPI(api, MultitenantConstants.SUPER_TENANT_ID, "testOrg"));
    ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
    // Add a subscription and update state to BLOCKED
    application.setId(applicationId);
    int subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.UNBLOCKED, "sub_user1");
    apiMgtDAO.updateSubscriptionStatus(subscriptionId, APIConstants.SubscriptionStatus.BLOCKED);
    // Add the second version of the API
    APIIdentifier apiId2 = new APIIdentifier("subForwardProvider", "SubForwardTestAPI", "V2.0.0");
    API api2 = new API(apiId2);
    api2.setContext("/context1");
    api2.setContextTemplate("/context1/{version}");
    api2.setUuid(UUID.randomUUID().toString());
    api2.getId().setId(apiMgtDAO.addAPI(api2, MultitenantConstants.SUPER_TENANT_ID, "testOrg"));
    // once API v2.0.0 is added, v1.0.0 becomes an older version hence add it to oldApiVersionList
    oldApiVersionList.add(api);
    ApiTypeWrapper apiTypeWrapper2 = new ApiTypeWrapper(api2);
    apiMgtDAO.makeKeysForwardCompatible(apiTypeWrapper2, oldApiVersionList);
    List<SubscribedAPI> subscriptionsOfAPI2 = apiMgtDAO.getSubscriptionsOfAPI(apiId2.getApiName(), "V2.0.0", apiId2.getProviderName());
    assertEquals(1, subscriptionsOfAPI2.size());
    SubscribedAPI blockedSubscription = subscriptionsOfAPI2.get(0);
    assertEquals(APIConstants.SubscriptionStatus.BLOCKED, blockedSubscription.getSubStatus());
    // update the BLOCKED subscription of the second API version to PROD_ONLY_BLOCKED
    apiMgtDAO.updateSubscription(apiId2, APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED, applicationId, "testOrg");
    // Add the third version of the API
    APIIdentifier apiId3 = new APIIdentifier("subForwardProvider", "SubForwardTestAPI", "V3.0.0");
    API api3 = new API(apiId3);
    api3.setContext("/context1");
    api3.setContextTemplate("/context1/{version}");
    api3.getId().setId(apiMgtDAO.addAPI(api3, MultitenantConstants.SUPER_TENANT_ID, "testOrg"));
    // Once API v2.0.0 is added, v2.0.0 becomes an older version hence add it to oldApiVersionList
    // This needs to be sorted as latest API last.
    oldApiVersionList.add(api2);
    ApiTypeWrapper apiTypeWrapper3 = new ApiTypeWrapper(api3);
    apiMgtDAO.makeKeysForwardCompatible(apiTypeWrapper3, oldApiVersionList);
    List<SubscribedAPI> subscriptionsOfAPI3 = apiMgtDAO.getSubscriptionsOfAPI(apiId1.getApiName(), "V3.0.0", apiId1.getProviderName());
    assertEquals(1, subscriptionsOfAPI3.size());
    SubscribedAPI prodOnlyBlockedSubscription = subscriptionsOfAPI3.get(0);
    assertEquals(APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED, prodOnlyBlockedSubscription.getSubStatus());
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application) Date(java.util.Date) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 Application (org.wso2.carbon.apimgt.api.model.Application)28 Tier (org.wso2.carbon.apimgt.api.model.Tier)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ArrayList (java.util.ArrayList)12 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)12 HashSet (java.util.HashSet)11 TreeMap (java.util.TreeMap)11 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 ResultSet (java.sql.ResultSet)9 JSONObject (net.minidev.json.JSONObject)9 API (org.wso2.carbon.apimgt.api.model.API)9