use of org.wso2.carbon.apimgt.api.model.Identifier 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);
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier 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);
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class EndpointAdminServiceProxyTestCase method testRemoveEndpointsToUpdate.
@Test
public void testRemoveEndpointsToUpdate() throws Exception {
EndpointAdminServiceProxy endpointAdminServiceProxy = null;
APIIdentifier identifier = null;
API api = null;
try {
endpointAdminServiceProxy = new EndpointAdminServiceProxy(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
EndpointAdmin endpointAdmin = Mockito.mock(EndpointAdmin.class);
String[] endpointNames = { "API1--v1.0.0_APIproductionEndpoint", "API1--v1.0.0_APIsandboxEndpoint" };
identifier = new APIIdentifier("P1_API1_1.0.0");
api = new API(identifier);
Mockito.when(endpointAdmin.getEndPointsNames()).thenReturn(endpointNames);
Mockito.when(endpointAdmin.getEndPointsNamesForTenant(Mockito.anyString())).thenReturn(endpointNames);
Mockito.when(endpointAdmin.deleteEndpoint(Mockito.anyString())).thenReturn(true);
Mockito.when(endpointAdmin.deleteEndpointForTenant(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
endpointAdminServiceProxy.setEndpointAdmin(endpointAdmin);
} catch (Exception e) {
Assert.fail("Exception while testing removeEndpointsToUpdate");
}
try {
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
} catch (AxisFault e) {
Assert.fail("AxisFault while testing removeEndpointsToUpdate");
}
try {
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
} catch (AxisFault e) {
Assert.fail("AxisFault while testing removeEndpointsToUpdate for tenant");
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class EndpointAdminServiceProxyTestCase method testRemoveEndpointsToUpdateAxisFault.
@Test
public void testRemoveEndpointsToUpdateAxisFault() throws Exception {
EndpointAdminServiceProxy endpointAdminServiceProxy = null;
APIIdentifier identifier = null;
API api = null;
endpointAdminServiceProxy = new EndpointAdminServiceProxy(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
identifier = new APIIdentifier("P1_API1_1.0.0");
api = new API(identifier);
try {
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
} catch (AxisFault e) {
// test for AxisFault
}
try {
endpointAdminServiceProxy.removeEndpointsToUpdate(api.getId().getApiName(), api.getId().getVersion());
} catch (AxisFault e) {
// test for AxisFault
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class WSO2APIPublisherTestCase method init.
@Before
public void init() throws Exception {
store = new APIStore();
store.setDisplayName(storeName);
store.setUsername(storeUserName);
store.setPassword(storePassword);
store.setEndpoint(storeEndpoint);
identifier = new APIIdentifier(apiIdentifier);
api = new API(identifier);
defaultHttpClient = Mockito.mock(CloseableHttpClient.class);
wso2APIPublisher = new WSO2APIPublisherWrapper(defaultHttpClient, username, Mockito.mock(APIProvider.class));
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
HttpEntity entity = Mockito.mock(HttpEntity.class);
statusLine = Mockito.mock(StatusLine.class);
Mockito.doReturn(statusLine).when(httpResponse).getStatusLine();
Mockito.doReturn(entity).when(httpResponse).getEntity();
PowerMockito.mockStatic(EntityUtils.class);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.EXTERNAL_API_STORES + "." + APIConstants.EXTERNAL_API_STORES_STORE_URL)).thenReturn(storeRedirectURL);
HttpGet httpGet = Mockito.mock(HttpGet.class);
HttpPost httpPost = Mockito.mock(HttpPost.class);
HttpDelete httpDelete = Mockito.mock(HttpDelete.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
PowerMockito.whenNew(HttpPost.class).withAnyArguments().thenReturn(httpPost);
PowerMockito.whenNew(HttpDelete.class).withAnyArguments().thenReturn(httpDelete);
Mockito.doReturn(httpResponse).when(defaultHttpClient).execute(httpPost);
Mockito.doReturn(httpResponse).when(defaultHttpClient).execute(httpGet);
Mockito.doReturn(httpResponse).when(defaultHttpClient).execute(httpDelete);
MultipartEntityBuilder multipartEntityBuilder = Mockito.mock(MultipartEntityBuilder.class);
PowerMockito.mockStatic(MultipartEntityBuilder.class);
Mockito.when(MultipartEntityBuilder.create()).thenReturn(multipartEntityBuilder);
Mockito.when(multipartEntityBuilder.build()).thenReturn(Mockito.mock(HttpEntity.class));
Mockito.doNothing().when(httpPost).setEntity(Matchers.any());
importExportAPI = Mockito.mock(ImportExportAPI.class);
}
Aggregations