use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.
the class APIMgtDAOTest method testDeleteSubscriptionsForapiId.
@Test
public void testDeleteSubscriptionsForapiId() throws Exception {
Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
String organization = "testOrg";
subscriber.setTenantId(-1234);
subscriber.setEmail("abc@wso2.com");
subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
apiMgtDAO.addSubscriber(subscriber, null);
Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) getSubscriptionPolicy("testCreateApplicationRegistrationEntry");
subscriptionPolicy.setMonetizationPlan(APIConstants.Monetization.FIXED_RATE);
apiMgtDAO.addSubscriptionPolicy((SubscriptionPolicy) subscriptionPolicy);
applicationPolicy.setTenantId(-1234);
apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
application.setTier("testCreateApplicationRegistrationEntry");
application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", organization));
application.setDescription("updated description");
apiMgtDAO.updateApplication(application);
assertEquals(apiMgtDAO.getApplicationById(application.getId()).getDescription(), "updated description");
APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
API api = new API(apiId);
api.setContext("/testCreateApplicationRegistrationEntry");
api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
APIPolicy apiPolicy = (APIPolicy) getPolicyAPILevelPerUser("testCreateApplicationRegistrationEntry");
api.setApiLevelPolicy(apiPolicy.getPolicyName());
api.setUUID(UUID.randomUUID().toString());
api.getId().setId(apiMgtDAO.addAPI(api, -1234, organization));
apiId.setTier(subscriptionPolicy.getPolicyName());
ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
int subsId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
assertTrue(apiMgtDAO.getApplicationsByTier(subscriptionPolicy.getPolicyName()).length > 0);
String subStatus = apiMgtDAO.getSubscriptionStatusById(subsId);
assertEquals(subStatus, APIConstants.SubscriptionStatus.ON_HOLD);
SubscribedAPI subscribedAPI = apiMgtDAO.getSubscriptionById(subsId);
String clientIdProduction = UUID.randomUUID().toString();
String clientIdSandbox = UUID.randomUUID().toString();
apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_PRODUCTION, application.getId(), clientIdProduction, "Default", UUID.randomUUID().toString());
apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_SANDBOX, application.getId(), clientIdSandbox, "Default", UUID.randomUUID().toString());
assertTrue(apiMgtDAO.getSubscriptionCount(subscriber, application.getName(), null) > 0);
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
Mockito.when(keyManager.retrieveApplication(clientIdProduction)).thenReturn(oAuthApplicationInfo);
Mockito.when(keyManager.retrieveApplication(clientIdSandbox)).thenReturn(oAuthApplicationInfo);
assertTrue(apiMgtDAO.getSubscribedAPIs(organization, subscriber, null).size() > 0);
assertEquals(subscribedAPI.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
assertEquals(subscribedAPI.getApiId(), apiId);
assertEquals(subscribedAPI.getApplication().getId(), application.getId());
SubscribedAPI subscribedAPIFromUuid = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
assertEquals(subscribedAPIFromUuid.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
assertEquals(subscribedAPIFromUuid.getApiId(), apiId);
assertEquals(subscribedAPIFromUuid.getApplication().getId(), application.getId());
apiMgtDAO.updateApplicationStatus(application.getId(), APIConstants.ApplicationStatus.APPLICATION_APPROVED);
String status = apiMgtDAO.getApplicationStatus("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry");
assertEquals(status, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
boolean applicationExist = apiMgtDAO.isApplicationExist(application.getName(), subscriber.getName(), null, organization);
assertTrue(applicationExist);
Set<SubscribedAPI> subscribedAPIS = apiMgtDAO.getSubscribedAPIs(subscriber, application.getName(), null);
assertEquals(subscribedAPIS.size(), 1);
apiMgtDAO.updateSubscription(apiId, APIConstants.SubscriptionStatus.BLOCKED, application.getId(), organization);
subscribedAPI.setSubStatus(APIConstants.SubscriptionStatus.REJECTED);
apiMgtDAO.updateSubscription(subscribedAPI);
assertTrue(apiMgtDAO.hasSubscription(subscriptionPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_SUB));
assertTrue(apiMgtDAO.hasSubscription(applicationPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_APP));
assertTrue(apiMgtDAO.hasSubscription(apiPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_API));
assertTrue(apiPolicy.getPolicyName().equals(apiMgtDAO.getAPILevelTier(apiMgtDAO.getAPIID(api.getUuid()))));
apiMgtDAO.recordAPILifeCycleEvent(api.getUuid(), "CREATED", "PUBLISHED", "testCreateApplicationRegistrationEntry", -1234);
apiMgtDAO.updateDefaultAPIPublishedVersion(apiId);
apiMgtDAO.removeAllSubscriptions(api.getUuid());
assertTrue(apiMgtDAO.getAPINamesMatchingContext(api.getContext()).size() > 0);
apiMgtDAO.deleteAPI(api.getUuid());
apiMgtDAO.deleteApplication(application);
apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
apiMgtDAO.deleteApplicationKeyMappingByConsumerKey(clientIdProduction);
apiMgtDAO.deleteApplicationMappingByConsumerKey(clientIdSandbox);
deleteSubscriber(subscriber.getId());
}
use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.
the class APIConsumerImpl method removeSubscription.
/**
* Removes a subscription specified by SubscribedAPI object
*
* @param subscription SubscribedAPI object
* @param organization Organization
* @throws APIManagementException
*/
@Override
public void removeSubscription(SubscribedAPI subscription, String organization) throws APIManagementException {
String uuid = subscription.getUUID();
if (subscription != null) {
Application application = subscription.getApplication();
Identifier identifier = subscription.getApiId() != null ? subscription.getApiId() : subscription.getProductId();
String userId = application.getSubscriber().getName();
removeSubscription(identifier, userId, application.getId(), organization);
if (log.isDebugEnabled()) {
String appName = application.getName();
String logMessage = "Identifier: " + identifier.toString() + " subscription (uuid : " + uuid + ") removed from app " + appName;
log.debug(logMessage);
}
// get the workflow state once the executor is executed.
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(application.getId()), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
// 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_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
}
} else {
SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
}
} else {
throw new APIManagementException(String.format("Subscription for UUID:%s does not exist.", subscription.getUUID()));
}
}
use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPIProductUsageByAPIProductId.
/**
* Returns usage details of a particular API
*
* @param apiProductId API Product identifier
* @return UserApplicationAPIUsages for given provider
* @throws org.wso2.carbon.apimgt.api.APIManagementException If failed to get UserApplicationAPIUsage
*/
@Override
public List<SubscribedAPI> getAPIProductUsageByAPIProductId(APIProductIdentifier apiProductId) throws APIManagementException {
APIProductIdentifier apiIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(apiProductId.getProviderName()), apiProductId.getName(), apiProductId.getVersion());
UserApplicationAPIUsage[] allApiProductResult = apiMgtDAO.getAllAPIProductUsageByProvider(apiProductId.getProviderName());
List<SubscribedAPI> subscribedAPIs = new ArrayList<>();
for (UserApplicationAPIUsage usage : allApiProductResult) {
for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) {
APIProductIdentifier subsApiProductId = apiSubscription.getProductId();
APIProductIdentifier subsApiProductIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(subsApiProductId.getProviderName()), subsApiProductId.getName(), subsApiProductId.getVersion());
if (subsApiProductIdEmailReplaced.equals(apiIdEmailReplaced)) {
subscribedAPIs.add(apiSubscription);
}
}
}
return subscribedAPIs;
}
use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.
the class InternalAPIKeyAuthenticatorTest method testAuthenticateWithExpiredToken.
@Test
public void testAuthenticateWithExpiredToken() 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("carbon.super");
Cache internalKeyCache = Mockito.mock(Cache.class);
PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn("carbon.super");
Cache internalKeyDataCache = Mockito.mock(Cache.class);
PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
Cache invalidCache = Mockito.mock(Cache.class);
PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
JWTTokenPayloadInfo jwtTokenPayloadInfo = new JWTTokenPayloadInfo();
jwtTokenPayloadInfo.setPayload(signedJWT.getJWTClaimsSet());
jwtTokenPayloadInfo.setAccessToken(internalKey);
String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
Mockito.when(internalKeyDataCache.get(cacheKey)).thenReturn(jwtTokenPayloadInfo);
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);
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);
}
use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.
the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCache.
@Test
public void testAuthenticateNoCache() 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("carbon.super");
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);
String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
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(false);
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);
AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
Assert.assertNotNull(authenticate);
Assert.assertTrue(authenticate.isMandatoryAuthentication());
Assert.assertTrue(authenticate.isAuthenticated());
Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
Assert.assertEquals(authenticate.getErrorCode(), 0);
Assert.assertNull(authenticate.getErrorMessage());
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(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
Mockito.verify(internalKeyDataCache, Mockito.times(1)).put(Mockito.anyString(), Mockito.any());
}
Aggregations