use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPIRevenue.
/**
* Get total revenue for a given API from all its' subscriptions
*
* @param apiId API ID
* @param messageContext message context
* @return revenue data for a given API
*/
@Override
public Response getAPIRevenue(String apiId, MessageContext messageContext) {
if (StringUtils.isBlank(apiId)) {
String errorMessage = "API ID cannot be empty or null when getting revenue details.";
RestApiUtil.handleBadRequest(errorMessage, log);
}
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
API api = apiProvider.getAPIbyUUID(apiId, organization);
if (!APIConstants.PUBLISHED.equalsIgnoreCase(api.getStatus())) {
String errorMessage = "API " + api.getId().getName() + " should be in published state to get total revenue.";
RestApiUtil.handleBadRequest(errorMessage, log);
}
Map<String, String> revenueUsageData = monetizationImplementation.getTotalRevenue(api, apiProvider);
APIRevenueDTO apiRevenueDTO = new APIRevenueDTO();
apiRevenueDTO.setProperties(revenueUsageData);
return Response.ok().entity(apiRevenueDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Failed to retrieve revenue data for API ID : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (MonetizationException e) {
String errorMessage = "Failed to get current revenue data for API ID : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method getSubscriptionUsage.
/**
* Get monetization usage data for a subscription
*
* @param subscriptionId subscription Id
* @param messageContext message context
* @return monetization usage data for a subscription
*/
@Override
public Response getSubscriptionUsage(String subscriptionId, MessageContext messageContext) {
if (StringUtils.isBlank(subscriptionId)) {
String errorMessage = "Subscription ID cannot be empty or null when getting monetization usage.";
RestApiUtil.handleBadRequest(errorMessage, log);
}
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
Map<String, String> billingEngineUsageData = monetizationImplementation.getCurrentUsageForSubscription(subscriptionId, apiProvider);
if (MapUtils.isEmpty(billingEngineUsageData)) {
String errorMessage = "Billing engine usage data was not found for subscription ID : " + subscriptionId;
RestApiUtil.handleBadRequest(errorMessage, log);
}
APIMonetizationUsageDTO apiMonetizationUsageDTO = new APIMonetizationUsageDTO();
apiMonetizationUsageDTO.setProperties(billingEngineUsageData);
return Response.ok().entity(apiMonetizationUsageDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Failed to retrieve billing engine usage data for subscription ID : " + subscriptionId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (MonetizationException e) {
String errorMessage = "Failed to get current usage for subscription ID : " + subscriptionId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.
the class ApiMgtDAO method getMonetizationUsagePublishInfo.
/**
* Derives info about monetization usage publish job
*
* @return ifno about the monetization usage publish job
* @throws APIManagementException
*/
public MonetizationUsagePublishInfo getMonetizationUsagePublishInfo() throws APIManagementException {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = APIMgtDBUtil.getConnection();
String query = SQLConstants.GET_MONETIZATION_USAGE_PUBLISH_INFO;
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
if (rs.next()) {
MonetizationUsagePublishInfo monetizationUsagePublishInfo = new MonetizationUsagePublishInfo();
monetizationUsagePublishInfo.setId(rs.getString("ID"));
monetizationUsagePublishInfo.setState(rs.getString("STATE"));
monetizationUsagePublishInfo.setStatus(rs.getString("STATUS"));
monetizationUsagePublishInfo.setStartedTime(rs.getLong("STARTED_TIME"));
monetizationUsagePublishInfo.setLastPublishTime(rs.getLong("PUBLISHED_TIME"));
return monetizationUsagePublishInfo;
}
} catch (SQLException e) {
handleException("Error while retrieving Monetization Usage Publish Info: ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIProduct.
@Override
public Map<API, List<APIProductResource>> updateAPIProduct(APIProduct product) throws APIManagementException, FaultGatewaysException {
Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
// validate resources and set api identifiers and resource ids to product
List<APIProductResource> resources = product.getProductResources();
for (APIProductResource apiProductResource : resources) {
API api;
APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
String apiUUID;
if (productIdentifier != null) {
APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
api = getAPIbyUUID(apiUUID, tenantDomain);
} else {
apiUUID = apiProductResource.getApiId();
api = getAPIbyUUID(apiUUID, tenantDomain);
}
if (api.getSwaggerDefinition() != null) {
api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, tenantDomain));
}
if (!apiToProductResourceMapping.containsKey(api)) {
apiToProductResourceMapping.put(api, new ArrayList<>());
}
List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
apiProductResources.add(apiProductResource);
// if API does not exist, getLightweightAPIByUUID() method throws exception. so no need to handle NULL
apiProductResource.setApiIdentifier(api.getId());
apiProductResource.setProductIdentifier(product.getId());
if (api.isAdvertiseOnly()) {
apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
apiProductResource.setEndpointConfig(api.getEndpointConfig());
}
apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
URITemplate uriTemplate = apiProductResource.getUriTemplate();
Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
if (uriTemplate == null) {
// TODO handle if no resource is defined. either throw an error or add all the resources of that API
// to the product
} else {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (templateMap.containsKey(key)) {
// Since the template ID is not set from the request, we manually set it.
uriTemplate.setId(templateMap.get(key).getId());
} else {
throw new APIManagementException("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getUriTemplate() + " with http method " + uriTemplate.getHTTPVerb());
}
}
}
APIProduct oldApi = getAPIProductbyUUID(product.getUuid(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
Gson gson = new Gson();
Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
Map<String, String> newMonetizationProperties = gson.fromJson(product.getMonetizationProperties().toString(), HashMap.class);
if (newMonetizationProperties != null) {
for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
String newValue = newMonetizationProperties.get(entry.getKey());
if (StringUtils.isAllBlank(newValue)) {
newMonetizationProperties.put(entry.getKey(), entry.getValue());
}
}
JSONParser parser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
product.setMonetizationProperties(jsonObj);
} catch (ParseException e) {
throw new APIManagementException("Error when parsing monetization properties ", e);
}
}
}
invalidateResourceCache(product.getContext(), product.getId().getVersion(), Collections.EMPTY_SET);
// todo : check whether permissions need to be updated and pass it along
updateApiProductArtifact(product, true, true);
apiMgtDAO.updateAPIProduct(product, userNameWithoutChange);
int productId = apiMgtDAO.getAPIProductId(product.getId());
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, product.getId().getName(), productId, product.getId().getUUID(), product.getId().getVersion(), product.getType(), product.getContext(), product.getId().getProviderName(), APIConstants.LC_PUBLISH_LC_STATE);
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
return apiToProductResourceMapping;
}
use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.
the class APIProviderImpl method configureMonetizationInAPIProductArtifact.
@Override
public void configureMonetizationInAPIProductArtifact(APIProduct apiProduct) throws APIManagementException {
boolean transactionCommitted = false;
try {
registry.beginTransaction();
String apiArtifactId = registry.get(APIUtil.getAPIProductPath(apiProduct.getId())).getId();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
handleException("Artifact manager is null when updating monetization data for API ID " + apiProduct.getId());
}
GenericArtifact artifact = artifactManager.getGenericArtifact(apiProduct.getUuid());
// set monetization status (i.e - enabled or disabled)
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(apiProduct.getMonetizationStatus()));
// clear existing monetization properties
artifact.removeAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
// set new additional monetization data
if (apiProduct.getMonetizationProperties() != null) {
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, apiProduct.getMonetizationProperties().toJSONString());
}
artifactManager.updateGenericArtifact(artifact);
registry.commitTransaction();
transactionCommitted = true;
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
handleException("Error while rolling back the transaction (monetization status update) for API product : " + apiProduct.getId().getName(), re);
}
handleException("Error while performing registry transaction (monetization status update) operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException e) {
handleException("Error occurred while rolling back the transaction (monetization status update).", e);
}
}
}
Aggregations