Search in sources :

Example 21 with Monetization

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;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIRevenueDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevenueDTO) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 22 with Monetization

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;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) APIMonetizationUsageDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationUsageDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 23 with Monetization

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;
}
Also used : MonetizationUsagePublishInfo(org.wso2.carbon.apimgt.api.model.MonetizationUsagePublishInfo) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 24 with Monetization

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;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) ArrayList(java.util.ArrayList) List(java.util.List) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 25 with Monetization

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);
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 JSONObject (org.json.simple.JSONObject)14 Tier (org.wso2.carbon.apimgt.api.model.Tier)14 API (org.wso2.carbon.apimgt.api.model.API)13 ArrayList (java.util.ArrayList)9 ParseException (org.json.simple.parser.ParseException)9 Monetization (org.wso2.carbon.apimgt.api.model.Monetization)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9 JSONParser (org.json.simple.parser.JSONParser)8 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)8 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)8 Gson (com.google.gson.Gson)7 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)7 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)7 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)7 HashMap (java.util.HashMap)6 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)6 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 HashSet (java.util.HashSet)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)5