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;
}
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);
}
}
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;
}
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();
}
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);
}
Aggregations