use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPIListToDTO.
/**
* Converts a List object of APIs into a DTO
*
* @param apiList List of APIs
* @return APIListDTO object containing APIDTOs
* @throws APIManagementException
*/
public static APIListDTO fromAPIListToDTO(List<Object> apiList, String organization) throws APIManagementException {
APIListDTO apiListDTO = new APIListDTO();
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
Map<String, Tier> tierMap = APIUtil.getTiers(organization);
List<APIInfoDTO> apiInfoDTOs = apiListDTO.getList();
if (apiList != null) {
for (Object api : apiList) {
APIInfoDTO apiInfoDTO = null;
if (api instanceof API) {
API api1 = (API) api;
apiInfoDTO = fromAPIToInfoDTO((API) api);
setThrottlePoliciesAndMonetization(api1, apiInfoDTO, deniedTiers, tierMap);
} else if (api instanceof APIProduct) {
APIProduct api1 = (APIProduct) api;
apiInfoDTO = fromAPIToInfoDTO((API) api);
setThrottlePoliciesAndMonetization(api1, apiInfoDTO, deniedTiers, tierMap);
}
apiInfoDTOs.add(apiInfoDTO);
}
}
apiListDTO.setCount(apiInfoDTOs.size());
return apiListDTO;
}
use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPIToInfoDTO.
/**
* Creates a minimal DTO representation of an API Product object
*
* @param apiProduct API Product object
* @return a minimal representation DTO
* @throws APIManagementException
*/
static APIInfoDTO fromAPIToInfoDTO(APIProduct apiProduct, String organization) throws APIManagementException {
APIInfoDTO apiInfoDTO = new APIInfoDTO();
apiInfoDTO.setDescription(apiProduct.getDescription());
apiInfoDTO.setContext(apiProduct.getContext());
apiInfoDTO.setId(apiProduct.getUuid());
APIProductIdentifier apiId = apiProduct.getId();
apiInfoDTO.setName(apiId.getName());
apiInfoDTO.setVersion(apiId.getVersion());
apiInfoDTO.setProvider(apiId.getProviderName());
apiInfoDTO.setLifeCycleStatus(apiProduct.getState());
apiInfoDTO.setType(APIType.API_PRODUCT.toString());
apiInfoDTO.setAvgRating(String.valueOf(apiProduct.getRating()));
String providerName = apiProduct.getId().getProviderName();
apiInfoDTO.setProvider(APIUtil.replaceEmailDomainBack(providerName));
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
Map<String, Tier> tierMap = APIUtil.getTiers(organization);
setThrottlePoliciesAndMonetization(apiProduct, apiInfoDTO, deniedTiers, tierMap);
APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
apiBusinessInformationDTO.setBusinessOwner(apiProduct.getBusinessOwner());
apiBusinessInformationDTO.setBusinessOwnerEmail(apiProduct.getBusinessOwnerEmail());
apiBusinessInformationDTO.setTechnicalOwner(apiProduct.getTechnicalOwner());
apiBusinessInformationDTO.setTechnicalOwnerEmail(apiProduct.getTechnicalOwnerEmail());
apiInfoDTO.setBusinessInformation(apiBusinessInformationDTO);
if (!StringUtils.isBlank(apiProduct.getThumbnailUrl())) {
apiInfoDTO.setThumbnailUri(apiProduct.getThumbnailUrl());
}
// Since same APIInfoDTO is used for listing APIProducts in StoreUI set default AdvertisedInfo to the DTO
AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
advertiseInfoDTO.setAdvertised(false);
apiInfoDTO.setAdvertiseInfo(advertiseInfoDTO);
String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiProduct.getId().getProviderName()));
String subscriptionAvailability = apiProduct.getSubscriptionAvailability();
String subscriptionAllowedTenants = apiProduct.getSubscriptionAvailableTenants();
apiInfoDTO.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
return apiInfoDTO;
}
use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPItoDTO.
public static APIDTO fromAPItoDTO(APIProduct model, String organization) throws APIManagementException {
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
APIDTO dto = new APIDTO();
dto.setName(model.getId().getName());
dto.setVersion(model.getId().getVersion());
String providerName = model.getId().getProviderName();
dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
dto.setId(model.getUuid());
dto.setContext(model.getContext());
dto.setDescription(model.getDescription());
dto.setLifeCycleStatus(model.getState());
dto.setType(model.getType());
dto.setAvgRating(String.valueOf(model.getRating()));
/* todo: created and last updated times
if (null != model.getLastUpdated()) {
Date lastUpdateDate = model.getLastUpdated();
Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
dto.setLastUpdatedTime(String.valueOf(timeStamp));
}
String createdTimeStamp = model.getCreatedTime();
if (null != createdTimeStamp) {
Date date = new Date(Long.valueOf(createdTimeStamp));
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String dateFormatted = formatter.format(date);
dto.setCreatedTime(dateFormatted);
} */
String apiDefinition = null;
if (model.isAsync()) {
// for asyncAPI retrieve asyncapi.yml specification
apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
} else {
// retrieve open API definition
if (model.getDefinition() != null) {
apiDefinition = model.getDefinition();
} else {
apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
}
}
dto.setApiDefinition(apiDefinition);
Set<String> apiTags = model.getTags();
List<String> tagsToReturn = new ArrayList<>();
tagsToReturn.addAll(apiTags);
dto.setTags(tagsToReturn);
Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
List<APITiersDTO> tiersToReturn = new ArrayList<>();
// set the monetization status of this API (enabled or disabled)
APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
monetizationInfoDTO.enabled(model.getMonetizationStatus());
dto.setMonetization(monetizationInfoDTO);
for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
APITiersDTO apiTiersDTO = new APITiersDTO();
apiTiersDTO.setTierName(currentTier.getName());
apiTiersDTO.setTierPlan(currentTier.getTierPlan());
// monetization attributes are applicable only for commercial tiers
if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
// check the billing plan (fixed or price per request)
if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
} else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
}
monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
}
apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
}
tiersToReturn.add(apiTiersDTO);
}
dto.setTiers(tiersToReturn);
List<APIOperationsDTO> operationList = new ArrayList<>();
Map<String, ScopeInfoDTO> uniqueScopes = new HashMap<>();
for (APIProductResource productResource : model.getProductResources()) {
URITemplate uriTemplate = productResource.getUriTemplate();
APIOperationsDTO operation = new APIOperationsDTO();
operation.setTarget(uriTemplate.getUriTemplate());
operation.setVerb(uriTemplate.getHTTPVerb());
operationList.add(operation);
List<Scope> scopes = uriTemplate.retrieveAllScopes();
for (Scope scope : scopes) {
if (!uniqueScopes.containsKey(scope.getKey())) {
ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles())) {
scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
}
uniqueScopes.put(scope.getKey(), scopeInfoDTO);
}
}
}
dto.setOperations(operationList);
dto.setScopes(new ArrayList<>(uniqueScopes.values()));
dto.setTransport(Arrays.asList(model.getTransports().split(",")));
APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
dto.setBusinessInformation(apiBusinessInformationDTO);
if (!StringUtils.isBlank(model.getThumbnailUrl())) {
dto.setHasThumbnail(true);
}
if (model.getAdditionalProperties() != null) {
JSONObject additionalProperties = model.getAdditionalProperties();
List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
for (Object propertyKey : additionalProperties.keySet()) {
APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
String key = (String) propertyKey;
int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
if (index > 0) {
additionalPropertiesDTO.setName(key.substring(0, index));
additionalPropertiesDTO.setDisplay(true);
additionalPropertiesList.add(additionalPropertiesDTO);
}
}
dto.setAdditionalProperties(additionalPropertiesList);
}
if (model.getEnvironments() != null) {
List<String> environmentListToReturn = new ArrayList<>(model.getEnvironments());
dto.setEnvironmentList(environmentListToReturn);
}
dto.setAuthorizationHeader(model.getAuthorizationHeader());
if (model.getApiSecurity() != null) {
dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
}
// Since same APIInfoDTO is used for APIProduct in StoreUI set default AdvertisedInfo to the DTO
AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
advertiseInfoDTO.setAdvertised(false);
dto.setAdvertiseInfo(advertiseInfoDTO);
String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
String subscriptionAvailability = model.getSubscriptionAvailability();
String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
return dto;
}
use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdThumbnailGet.
@Override
public Response apisApiIdThumbnailGet(String apiId, String xWSO2Tenant, String ifNoneMatch, MessageContext messageContext) {
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
// this will fail if user does not have access to the API or the API does not exist
apiConsumer.getLightweightAPIByUUID(apiId, organization);
ResourceFile thumbnailResource = apiConsumer.getIcon(apiId, organization);
if (thumbnailResource != null) {
return Response.ok(thumbnailResource.getContent(), MediaType.valueOf(thumbnailResource.getContentType())).build();
} else {
return Response.noContent().build();
}
} catch (APIManagementException e) {
// existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
String errorMessage = "Error while retrieving thumbnail of API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisGet.
@Override
public Response apisGet(Integer limit, Integer offset, String xWSO2Tenant, String query, String ifNoneMatch, MessageContext messageContext) {
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
query = query == null ? "" : query;
APIListDTO apiListDTO = new APIListDTO();
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
// revert content search back to normal search by name to avoid doc result complexity and to comply with REST api practices
if (query.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":")) {
query = query.replace(APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":", APIConstants.NAME_TYPE_PREFIX + ":");
}
Map allMatchedApisMap = apiConsumer.searchPaginatedAPIs(query, organization, offset, limit, null, null);
// This is a SortedSet
Set<Object> sortedSet = (Set<Object>) allMatchedApisMap.get("apis");
ArrayList<Object> allMatchedApis = new ArrayList<>(sortedSet);
apiListDTO = APIMappingUtil.fromAPIListToDTO(allMatchedApis, organization);
// Add pagination section in the response
Object totalLength = allMatchedApisMap.get("length");
Integer totalAvailableAPis = 0;
if (totalLength != null) {
totalAvailableAPis = (Integer) totalLength;
}
APIMappingUtil.setPaginationParams(apiListDTO, query, offset, limit, totalAvailableAPis);
return Response.ok().entity(apiListDTO).build();
} catch (APIManagementException e) {
if (RestApiUtil.rootCauseMessageMatches(e, "start index seems to be greater than the limit count")) {
// this is not an error of the user as he does not know the total number of apis available. Thus sends
// an empty response
apiListDTO.setCount(0);
apiListDTO.setPagination(new PaginationDTO());
return Response.ok().entity(apiListDTO).build();
} else {
String errorMessage = "Error while retrieving APIs";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
Aggregations