use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class APIConsumerImpl method addTiersToAPI.
private APIProduct addTiersToAPI(APIProduct apiProduct, String organization) throws APIManagementException {
int tenantId = APIUtil.getInternalIdFromTenantDomainOrOrganization(organization);
Set<Tier> tierNames = apiProduct.getAvailableTiers();
Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
Set<Tier> availableTiers = new HashSet<>();
Set<String> deniedTiers = getDeniedTiers(tenantId);
for (Tier tierName : tierNames) {
Tier definedTier = definedTiers.get(tierName.getName());
if (definedTier != null) {
availableTiers.add(definedTier);
}
}
availableTiers.removeIf(tier -> deniedTiers.contains(tier.getName()));
apiProduct.removeAllTiers();
apiProduct.setAvailableTiers(availableTiers);
return apiProduct;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class APIConsumerImpl method filterMultipleVersionedAPIs.
private Map<String, Object> filterMultipleVersionedAPIs(Map<String, Object> searchResults) {
Object apiObj = searchResults.get("apis");
ArrayList<Object> apiSet;
ArrayList<APIProduct> apiProductSet = new ArrayList<>();
if (apiObj instanceof Set) {
apiSet = new ArrayList<>(((Set) apiObj));
} else {
apiSet = (ArrayList<Object>) apiObj;
}
// Store the length of the APIs list with the versioned APIs
int apiSetLengthWithVersionedApis = apiSet.size();
int totalLength = Integer.parseInt(searchResults.get("length").toString());
// filter store results if displayMultipleVersions is set to false
Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
if (!displayMultipleVersions) {
SortedSet<API> resultApis = new TreeSet<API>(new APINameComparator());
for (Object result : apiSet) {
if (result instanceof API) {
resultApis.add((API) result);
} else if (result instanceof Map.Entry) {
Map.Entry<Documentation, API> entry = (Map.Entry<Documentation, API>) result;
resultApis.add(entry.getValue());
} else if (result instanceof APIProduct) {
apiProductSet.add((APIProduct) result);
}
}
Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
Comparator<API> versionComparator = new APIVersionComparator();
String key;
// Run the result api list through API version comparator and filter out multiple versions
for (API api : resultApis) {
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
}
// filter apiSet
ArrayList<Object> tempApiSet = new ArrayList<Object>();
for (Object result : apiSet) {
API api = null;
String mapKey;
API latestAPI;
if (result instanceof API) {
api = (API) result;
mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
if (latestPublishedAPIs.containsKey(mapKey)) {
latestAPI = latestPublishedAPIs.get(mapKey);
if (latestAPI.getId().equals(api.getId())) {
tempApiSet.add(api);
}
}
} else if (result instanceof Map.Entry) {
Map.Entry<Documentation, API> docEntry = (Map.Entry<Documentation, API>) result;
api = docEntry.getValue();
mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
if (latestPublishedAPIs.containsKey(mapKey)) {
latestAPI = latestPublishedAPIs.get(mapKey);
if (latestAPI.getId().equals(api.getId())) {
tempApiSet.add(docEntry);
}
}
}
}
// Store the length of the APIs list without the versioned APIs
int apiSetLengthWithoutVersionedApis = tempApiSet.size();
apiSet = tempApiSet;
ArrayList<Object> resultAPIandProductSet = new ArrayList<>();
resultAPIandProductSet.addAll(apiSet);
resultAPIandProductSet.addAll(apiProductSet);
resultAPIandProductSet.sort(new ContentSearchResultNameComparator());
if (apiObj instanceof Set) {
searchResults.put("apis", new LinkedHashSet<>(resultAPIandProductSet));
} else {
searchResults.put("apis", resultAPIandProductSet);
}
searchResults.put("length", totalLength - (apiSetLengthWithVersionedApis - (apiSetLengthWithoutVersionedApis + apiProductSet.size())));
}
return searchResults;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct 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.APIProduct in project carbon-apimgt by wso2.
the class APIConfigContext method setApiProductVelocityContext.
private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
APIProductIdentifier id = apiProduct.getId();
// set the api name version and context
context.put("apiName", PRODUCT_PREFIX + "--" + id.getName());
context.put("apiVersion", "1.0.0");
// We set the context pattern now to support plugable version strategy
// context.put("apiContext", api.getContext());
context.put("apiContext", apiProduct.getContext());
// the api object will be passed on to the template so it properties can be used to
// customise how the synapse config is generated.
context.put("apiObj", apiProduct);
context.put("apiIsBlocked", Boolean.FALSE);
String apiSecurity = apiProduct.getApiSecurity();
// if API is secured with ouath2
if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
context.put("apiIsOauthProtected", Boolean.TRUE);
} else {
context.put("apiIsOauthProtected", Boolean.FALSE);
}
// if API is secured with api_Key
if (apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
context.put("apiIsApiKeyProtected", Boolean.TRUE);
} else {
context.put("apiIsApiKeyProtected", Boolean.FALSE);
}
// if API is secured with basic_auth
if (apiSecurity.contains(APIConstants.API_SECURITY_BASIC_AUTH)) {
context.put("apiIsBasicAuthProtected", Boolean.TRUE);
} else {
context.put("apiIsBasicAuthProtected", Boolean.FALSE);
}
if (apiProduct.isEnabledSchemaValidation()) {
context.put("enableSchemaValidation", Boolean.TRUE);
} else {
context.put("enableSchemaValidation", Boolean.FALSE);
}
if (apiProduct.isEnableStore()) {
context.put("enableStore", Boolean.TRUE);
} else {
context.put("enableStore", Boolean.FALSE);
}
// API test key
context.put("testKey", apiProduct.getTestKey());
context.put("apiType", apiProduct.getType());
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class APIMappingUtil method setAPICategoriesToModel.
/**
* Set API categories to API or APIProduct based on the instance type of the DTO object passes.
*
* @param dto APIDTO or APIProductDTO
* @param model API or APIProduct
*/
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
List<String> apiCategoryNames = new ArrayList<>();
if (dto instanceof APIDTO) {
APIDTO apiDTO = (APIDTO) dto;
apiCategoryNames = apiDTO.getCategories();
} else {
APIProductDTO apiProductDTO = (APIProductDTO) dto;
apiCategoryNames = apiProductDTO.getCategories();
}
List<APICategory> apiCategories = new ArrayList<>();
for (String categoryName : apiCategoryNames) {
APICategory category = new APICategory();
category.setName(categoryName);
apiCategories.add(category);
}
if (model instanceof API) {
((API) model).setApiCategories(apiCategories);
} else {
((APIProduct) model).setApiCategories(apiCategories);
}
}
Aggregations