use of org.wso2.carbon.apimgt.api.model.APIProduct 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.model.APIProduct in project carbon-apimgt by wso2.
the class SearchApiServiceImpl method searchGet.
@Override
public Response searchGet(Integer limit, Integer offset, String xWSO2Tenant, String query, String ifNoneMatch, MessageContext messageContext) {
SearchResultListDTO resultListDTO = new SearchResultListDTO();
List<SearchResultDTO> allmatchedResults = new ArrayList<>();
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
query = query == null ? "*" : query;
String organization = RestApiUtil.getOrganization(messageContext);
try {
if (!query.contains(":")) {
query = (APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":" + query);
}
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
Map<String, Object> result = null;
// Extracting search queries for the recommendation system
apiConsumer.publishSearchQuery(query, username);
if (query.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX)) {
result = apiConsumer.searchPaginatedContent(query, organization, offset, limit);
} else {
result = apiConsumer.searchPaginatedAPIs(query, organization, offset, limit, null, null);
}
ArrayList<Object> apis;
/* Above searchPaginatedAPIs method underneath calls searchPaginatedAPIsByContent method,searchPaginatedAPIs
method and searchAPIDoc method in AbstractApiManager. And those methods respectively returns ArrayList,
TreeSet and a HashMap.
Hence the below logic.
*/
Object apiSearchResults = result.get("apis");
if (apiSearchResults instanceof List<?>) {
apis = (ArrayList<Object>) apiSearchResults;
} else if (apiSearchResults instanceof HashMap) {
Collection<String> values = ((HashMap) apiSearchResults).values();
apis = new ArrayList<Object>(values);
} else {
apis = new ArrayList<Object>();
apis.addAll((Collection<?>) apiSearchResults);
}
for (Object searchResult : apis) {
if (searchResult instanceof API) {
API api = (API) searchResult;
SearchResultDTO apiResult = SearchResultMappingUtil.fromAPIToAPIResultDTO(api);
allmatchedResults.add(apiResult);
} else if (searchResult instanceof Map.Entry) {
Map.Entry pair = (Map.Entry) searchResult;
SearchResultDTO docResult = SearchResultMappingUtil.fromDocumentationToDocumentResultDTO((Documentation) pair.getKey(), (API) pair.getValue());
allmatchedResults.add(docResult);
} else if (searchResult instanceof APIProduct) {
APIProduct apiProduct = (APIProduct) searchResult;
SearchResultDTO apiResult = SearchResultMappingUtil.fromAPIToAPIResultDTO(apiProduct);
allmatchedResults.add(apiResult);
}
}
Object totalLength = result.get("length");
Integer length = 0;
if (totalLength != null) {
length = (Integer) totalLength;
}
List<Object> allmatchedObjectResults = new ArrayList<>(allmatchedResults);
resultListDTO.setList(allmatchedObjectResults);
resultListDTO.setCount(allmatchedResults.size());
SearchResultMappingUtil.setPaginationParams(resultListDTO, query, offset, limit, length);
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving search results";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return Response.ok().entity(resultListDTO).build();
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class SearchResultMappingUtil method fromAPIToAPIResultDTO.
/**
* Get API result representation for content search
* @param apiProduct API product
* @return APISearchResultDTO
*/
public static APISearchResultDTO fromAPIToAPIResultDTO(APIProduct apiProduct) {
APISearchResultDTO apiResultDTO = new APISearchResultDTO();
apiResultDTO.setId(apiProduct.getUuid());
APIProductIdentifier apiId = apiProduct.getId();
apiResultDTO.setName(apiId.getName());
apiResultDTO.setVersion(apiId.getVersion());
apiResultDTO.setProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
String context = apiProduct.getContextTemplate();
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
apiResultDTO.setContext(context);
apiResultDTO.setAvgRating(String.valueOf(apiProduct.getRating()));
APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
apiBusinessInformationDTO.setBusinessOwner(apiProduct.getBusinessOwner());
apiBusinessInformationDTO.setBusinessOwnerEmail(apiProduct.getBusinessOwnerEmail());
apiBusinessInformationDTO.setTechnicalOwner(apiProduct.getTechnicalOwner());
apiBusinessInformationDTO.setTechnicalOwnerEmail(apiProduct.getTechnicalOwnerEmail());
apiResultDTO.setBusinessInformation(apiBusinessInformationDTO);
apiResultDTO.setType(SearchResultDTO.TypeEnum.API);
apiResultDTO.setTransportType(apiProduct.getType());
apiResultDTO.setDescription(apiProduct.getDescription());
apiResultDTO.setStatus(apiProduct.getState());
apiResultDTO.setThumbnailUri(apiProduct.getThumbnailUrl());
return apiResultDTO;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class SubscriptionMappingUtil method fromSubscriptionToDTO.
public static SubscriptionDTO fromSubscriptionToDTO(SubscribedAPI subscription, ApiTypeWrapper apiTypeWrapper, String organization) throws APIManagementException {
SubscriptionDTO subscriptionDTO = new SubscriptionDTO();
subscriptionDTO.setSubscriptionId(subscription.getUUID());
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
Map<String, Tier> tierMap = APIUtil.getTiers(organization);
if (apiTypeWrapper != null && !apiTypeWrapper.isAPIProduct()) {
API api = apiTypeWrapper.getApi();
subscriptionDTO.setApiId(api.getUUID());
APIInfoDTO apiInfo = APIMappingUtil.fromAPIToInfoDTO(api);
APIMappingUtil.setThrottlePoliciesAndMonetization(api, apiInfo, deniedTiers, tierMap);
subscriptionDTO.setApiInfo(apiInfo);
} else {
APIProduct apiProduct = apiTypeWrapper.getApiProduct();
subscriptionDTO.setApiId(apiProduct.getUuid());
APIInfoDTO apiInfo = APIMappingUtil.fromAPIToInfoDTO(apiProduct, organization);
APIMappingUtil.setThrottlePoliciesAndMonetization(apiProduct, apiInfo, deniedTiers, tierMap);
subscriptionDTO.setApiInfo(apiInfo);
}
Application application = subscription.getApplication();
subscriptionDTO.setApplicationId(subscription.getApplication().getUUID());
subscriptionDTO.setStatus(SubscriptionDTO.StatusEnum.valueOf(subscription.getSubStatus()));
subscriptionDTO.setThrottlingPolicy(subscription.getTier().getName());
subscriptionDTO.setRequestedThrottlingPolicy(subscription.getRequestedTier().getName());
ApplicationInfoDTO applicationInfoDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(application);
subscriptionDTO.setApplicationInfo(applicationInfoDTO);
return subscriptionDTO;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAPIProduct.
/**
* Get API Product by product identifier
*
* @param identifier APIProductIdentifier
* @return API product identified by provider identifier
* @throws APIManagementException
*/
public APIProduct getAPIProduct(APIProductIdentifier identifier) throws APIManagementException {
String apiProductPath = APIUtil.getAPIProductPath(identifier);
Registry registry;
try {
String productTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
int productTenantId = getTenantManager().getTenantId(productTenantDomain);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(productTenantDomain)) {
APIUtil.loadTenantRegistry(productTenantId);
}
if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) {
// cross tenant scenario
registry = getRegistryService().getGovernanceUserRegistry(getTenantAwareUsername(APIUtil.replaceEmailDomainBack(identifier.getProviderName())), productTenantId);
} else {
registry = this.registry;
}
GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
Resource productResource = registry.get(apiProductPath);
String artifactId = productResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiProductPath);
}
GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId);
APIProduct apiProduct = APIUtil.getAPIProduct(productArtifact, registry);
return apiProduct;
} catch (RegistryException e) {
String msg = "Failed to get API Product from : " + apiProductPath;
throw new APIManagementException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Failed to get API Product from : " + apiProductPath;
throw new APIManagementException(msg, e);
}
}
Aggregations