Search in sources :

Example 11 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class DefaultMonetizationImpl method publishMonetizationUsageRecords.

/**
 * Update info about monetization usage publish job
 *
 * @param monetizationUsagePublishInfo
 * @return boolean always return true if there is no exception
 * @throws MonetizationException
 */
@Override
public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo monetizationUsagePublishInfo) throws MonetizationException {
    APIAdmin apiAdmin = new APIAdminImpl();
    monetizationUsagePublishInfo.setState(APIConstants.Monetization.COMPLETED);
    monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.SUCCESSFULL);
    DateFormat df = new SimpleDateFormat(APIConstants.Monetization.USAGE_PUBLISH_TIME_FORMAT);
    Date dateobj = new Date();
    // get the time in UTC format
    df.setTimeZone(TimeZone.getTimeZone(APIConstants.Monetization.USAGE_PUBLISH_TIME_ZONE));
    String currentDate = df.format(dateobj);
    long currentTimestamp = apiAdmin.getTimestamp(currentDate);
    monetizationUsagePublishInfo.setLastPublishTime(currentTimestamp);
    try {
        apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
    } catch (APIManagementException e) {
        throw new MonetizationException("Failed to update the monetization usage publish info", e);
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 12 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class MonetizationUsagePublishAgent method run.

@Override
public void run() {
    Monetization monetizationImpl = null;
    APIAdmin apiAdmin = null;
    try {
        apiAdmin = new APIAdminImpl();
        monetizationImpl = apiAdmin.getMonetizationImplClass();
        monetizationUsagePublishInfo.setState(APIConstants.Monetization.RUNNING);
        monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.INPROGRESS);
        DateFormat df = new SimpleDateFormat(APIConstants.Monetization.USAGE_PUBLISH_TIME_FORMAT);
        Date dateobj = new Date();
        df.setTimeZone(TimeZone.getTimeZone(APIConstants.Monetization.USAGE_PUBLISH_TIME_ZONE));
        String currentDate = df.format(dateobj);
        long currentTimestamp = apiAdmin.getTimestamp(currentDate);
        // set the current time as starting time of the job
        monetizationUsagePublishInfo.setStartedTime(currentTimestamp);
        apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
        monetizationImpl.publishMonetizationUsageRecords(monetizationUsagePublishInfo);
    } catch (Exception e) {
        try {
            // update the state and status of the job incase of any execptions
            monetizationUsagePublishInfo.setState(APIConstants.Monetization.COMPLETED);
            monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.FAILED);
            apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
        } catch (APIManagementException ex) {
            String errorMsg = "Failed to update the state of monetization ussge publisher";
            log.error(errorMsg, ex);
        }
        String errorMsg = "Failed to publish monetization usage to billing Engine";
        log.error(errorMsg, e);
    }
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 13 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIMappingUtil method getMonetizationInfoDTO.

/**
 * This method creates the API monetization information DTO.
 *
 * @param apiId API apiid
 * @param organization identifier of the organization
 * @return monetization information DTO
 * @throws APIManagementException if failed to construct the DTO
 */
public static APIMonetizationInfoDTO getMonetizationInfoDTO(String apiId, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
    APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
    // set the information relatated to monetization to the DTO
    apiMonetizationInfoDTO.setEnabled(api.getMonetizationStatus());
    Map<String, String> monetizationPropertiesMap = new HashMap<>();
    if (api.getMonetizationProperties() != null) {
        JSONObject monetizationProperties = api.getMonetizationProperties();
        for (Object propertyKey : monetizationProperties.keySet()) {
            String key = (String) propertyKey;
            monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
        }
    }
    apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
    return apiMonetizationInfoDTO;
}
Also used : JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)

Example 14 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIMonetization.

/**
 * Monetize (enable or disable) for a given API
 *
 * @param apiId API ID
 * @param body request body
 * @param messageContext message context
 * @return monetizationDTO
 */
@Override
public Response addAPIMonetization(String apiId, APIMonetizationInfoDTO body, MessageContext messageContext) {
    try {
        if (StringUtils.isBlank(apiId)) {
            String errorMessage = "API ID cannot be empty or null when configuring monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifier == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        if (!APIConstants.PUBLISHED.equalsIgnoreCase(api.getStatus())) {
            String errorMessage = "API " + apiIdentifier.getApiName() + " should be in published state to configure monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        // set the monetization status
        boolean monetizationEnabled = body.isEnabled();
        api.setMonetizationStatus(monetizationEnabled);
        // clear the existing properties related to monetization
        api.getMonetizationProperties().clear();
        Map<String, String> monetizationProperties = body.getProperties();
        if (MapUtils.isNotEmpty(monetizationProperties)) {
            String errorMessage = RestApiPublisherUtils.validateMonetizationProperties(monetizationProperties);
            if (!errorMessage.isEmpty()) {
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
            for (Map.Entry<String, String> currentEntry : monetizationProperties.entrySet()) {
                api.addMonetizationProperty(currentEntry.getKey(), currentEntry.getValue());
            }
        }
        Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
        HashMap monetizationDataMap = new Gson().fromJson(api.getMonetizationProperties().toString(), HashMap.class);
        boolean isMonetizationStateChangeSuccessful = false;
        if (MapUtils.isEmpty(monetizationDataMap)) {
            String errorMessage = "Monetization is not configured. Monetization data is empty for " + apiIdentifier.getApiName();
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        try {
            if (monetizationEnabled) {
                isMonetizationStateChangeSuccessful = monetizationImplementation.enableMonetization(organization, api, monetizationDataMap);
            } else {
                isMonetizationStateChangeSuccessful = monetizationImplementation.disableMonetization(organization, api, monetizationDataMap);
            }
        } catch (MonetizationException e) {
            String errorMessage = "Error while changing monetization status for API ID : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
        if (isMonetizationStateChangeSuccessful) {
            apiProvider.configureMonetizationInAPIArtifact(api);
            APIMonetizationInfoDTO monetizationInfoDTO = APIMappingUtil.getMonetizationInfoDTO(apiId, organization);
            return Response.ok().entity(monetizationInfoDTO).build();
        } else {
            String errorMessage = "Unable to change monetization status for API : " + apiId;
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while configuring monetization for API ID : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return Response.serverError().build();
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)

Example 15 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class PublisherCommonUtils method updateApiProduct.

/**
 * Update an API Product.
 *
 * @param originalAPIProduct    Existing API Product
 * @param apiProductDtoToUpdate New API Product DTO to update
 * @param apiProvider           API Provider
 * @param username              Username
 * @throws APIManagementException If an error occurs while retrieving and updating an existing API Product
 * @throws FaultGatewaysException If an error occurs while updating an existing API Product
 */
public static APIProduct updateApiProduct(APIProduct originalAPIProduct, APIProductDTO apiProductDtoToUpdate, APIProvider apiProvider, String username, String orgId) throws APIManagementException, FaultGatewaysException {
    List<String> apiSecurity = apiProductDtoToUpdate.getSecurityScheme();
    // validation for tiers
    List<String> tiersFromDTO = apiProductDtoToUpdate.getPolicies();
    if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
        if (tiersFromDTO == null || tiersFromDTO.isEmpty()) {
            throw new APIManagementException("No tier defined for the API Product", ExceptionCodes.TIER_CANNOT_BE_NULL);
        }
    }
    // check whether the added API Products's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = PublisherCommonUtils.getInvalidTierNames(definedTiers, tiersFromDTO);
    if (!invalidTiers.isEmpty()) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    if (apiProductDtoToUpdate.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDtoToUpdate.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, originalAPIProduct.getId().getName(), originalAPIProduct.getId().getVersion()));
        }
    }
    APIProduct product = APIMappingUtil.fromDTOtoAPIProduct(apiProductDtoToUpdate, username);
    product.setState(originalAPIProduct.getState());
    // We do not allow to modify provider,name,version  and uuid. Set the origial value
    APIProductIdentifier productIdentifier = originalAPIProduct.getId();
    product.setID(productIdentifier);
    product.setUuid(originalAPIProduct.getUuid());
    product.setOrganization(orgId);
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.updateAPIProduct(product);
    apiProvider.updateAPIProductSwagger(originalAPIProduct.getUuid(), apiToProductResourceMapping, product, orgId);
    // preserve monetization status in the update flow
    apiProvider.configureMonetizationInAPIProductArtifact(product);
    return apiProvider.getAPIProduct(productIdentifier);
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList)

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