use of org.wso2.carbon.apimgt.api.model.APIProductResource 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.APIProductResource in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addAPIProductWithGeneratedSwaggerDefinition.
/**
* Add API Product with the generated swagger from the DTO.
*
* @param apiProductDTO API Product DTO
* @param username Username
* @param organization Identifier of the organization
* @return Created API Product object
* @throws APIManagementException Error while creating the API Product
* @throws FaultGatewaysException Error while adding the API Product to gateway
*/
public static APIProduct addAPIProductWithGeneratedSwaggerDefinition(APIProductDTO apiProductDTO, String username, String organization) throws APIManagementException, FaultGatewaysException {
username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
// if not add product
String provider = apiProductDTO.getProvider();
String context = apiProductDTO.getContext();
if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
if (log.isDebugEnabled()) {
log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
}
provider = username;
}
} else {
// Set username in case provider is null or empty
provider = username;
}
List<String> tiersFromDTO = apiProductDTO.getPolicies();
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 (apiProductDTO.getAdditionalProperties() != null) {
String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDTO.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiProductDTO.getName()));
}
}
if (apiProductDTO.getVisibility() == null) {
// set the default visibility to PUBLIC
apiProductDTO.setVisibility(APIProductDTO.VisibilityEnum.PUBLIC);
}
if (apiProductDTO.getAuthorizationHeader() == null) {
apiProductDTO.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
}
if (apiProductDTO.getAuthorizationHeader() == null) {
apiProductDTO.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
}
// Remove the /{version} from the context.
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
// Make sure context starts with "/". ex: /pizzaProduct
context = context.startsWith("/") ? context : ("/" + context);
// Check whether the context already exists
if (apiProvider.isContextExist(context)) {
throw new APIManagementException("Error occurred while adding API Product. API Product with the context " + context + " already " + "exists.", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_CONTEXT_ALREADY_EXISTS, context));
}
// Set default gatewayVendor
if (apiProductDTO.getGatewayVendor() == null) {
apiProductDTO.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
}
APIProduct productToBeAdded = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, provider);
productToBeAdded.setOrganization(organization);
if (!APIConstants.PROTOTYPED.equals(productToBeAdded.getState())) {
productToBeAdded.setState(APIConstants.CREATED);
}
APIProductIdentifier createdAPIProductIdentifier = productToBeAdded.getId();
Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.addAPIProductWithoutPublishingToGateway(productToBeAdded);
APIProduct createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
apiProvider.addAPIProductSwagger(createdProduct.getUuid(), apiToProductResourceMapping, createdProduct, organization);
createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
return createdProduct;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class ResourceConfigContextTest method getAPIProductResources.
private List<APIProductResource> getAPIProductResources(APIProductIdentifier apiProductIdentifier) {
APIProductResource apiProductResource = new APIProductResource();
apiProductResource.setApiIdentifier(new APIIdentifier("admin", "api1", "1.0.0", UUID.randomUUID().toString()));
URITemplate template = new URITemplate();
template.setUriTemplate("/test");
template.setHTTPVerb("GET");
template.setThrottlingTier("Unlimited");
template.setAuthType("Application");
template.setResourceURI("http://maps.googleapis.com/maps/api/geocode/json?address=Colombo");
template.setResourceSandboxURI("http://maps.googleapis.com/maps/api/geocode/json?address=Colombo");
apiProductResource.setProductIdentifier(apiProductIdentifier);
apiProductResource.setUriTemplate(template);
return Arrays.asList(new APIProductResource[] { apiProductResource });
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class SecurityConfigContext method getContext.
public VelocityContext getContext() {
VelocityContext context = super.getContext();
boolean isSecureVaultEnabled = Boolean.parseBoolean(getApiManagerConfiguration().getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE));
if (api != null) {
Map<String, EndpointSecurityModel> endpointSecurityModelMap = new HashMap<>();
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, new EndpointSecurityModel());
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, new EndpointSecurityModel());
if (StringUtils.isNotEmpty(api.getEndpointConfig())) {
if (productionEndpointSecurity != null) {
EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(productionEndpointSecurity, EndpointSecurityModel.class);
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_PRODUCTION, null);
if (endpointSecurityModel != null) {
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityModel);
}
}
if (sandboxEndpointSecurity != null) {
EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(sandboxEndpointSecurity, EndpointSecurityModel.class);
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_SANDBOX, null);
if (endpointSecurityModel != null) {
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecurityModel);
}
}
}
context.put("endpoint_security", endpointSecurityModelMap);
} else if (apiProduct != null) {
Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = new HashMap<>();
for (APIProductResource apiProductResource : apiProduct.getProductResources()) {
APIDTO apidto = associatedAPIMap.get(apiProductResource.getApiId());
String alias = apiProduct.getId().getName() + "--v" + apiProduct.getId().getVersion();
Map<String, EndpointSecurityModel> stringEndpointSecurityModelMap = new HashMap<>();
Map<String, EndpointSecurity> endpointSecurityMap = apiProductResource.getEndpointSecurityMap();
for (Map.Entry<String, EndpointSecurity> endpointSecurityEntry : endpointSecurityMap.entrySet()) {
EndpointSecurityModel endpointSecurityModel = new EndpointSecurityModel(endpointSecurityEntry.getValue());
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, apidto.getName(), apidto.getVersion(), apidto.getId(), endpointSecurityEntry.getKey(), alias);
stringEndpointSecurityModelMap.put(endpointSecurityEntry.getKey(), endpointSecurityModel);
}
endpointSecurityModelMap.put(apiProductResource.getApiId(), stringEndpointSecurityModelMap);
}
context.put("endpoint_security", endpointSecurityModelMap);
}
context.put("isSecureVaultEnabled", isSecureVaultEnabled);
return context;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class ApiProductsApiServiceImpl method updateAPIProductThumbnail.
@Override
public Response updateAPIProductThumbnail(String apiProductId, InputStream fileInputStream, Attachment fileDetail, String ifMatch, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
String fileName = fileDetail.getDataHandler().getName();
String extension = FilenameUtils.getExtension(fileName);
if (!RestApiConstants.ALLOWED_THUMBNAIL_EXTENSIONS.contains(extension.toLowerCase())) {
RestApiUtil.handleBadRequest("Unsupported Thumbnail File Extension. Supported extensions are .jpg, .png, .jpeg .svg " + "and .gif", log);
}
String fileContentType = URLConnection.guessContentTypeFromName(fileName);
if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
fileContentType = fileDetail.getContentType().toString();
}
// this will fail if user does not have access to the API or the API does not exist
APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
ResourceFile apiImage = new ResourceFile(fileInputStream, fileContentType);
apiProvider.setThumbnailToAPI(apiProductId, apiImage, tenantDomain);
/*
String thumbPath = APIUtil.getProductIconPath(apiProduct.getId());
String thumbnailUrl = apiProvider.addProductResourceFile(apiProduct.getId(), thumbPath, apiImage);
apiProduct.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, apiProduct.getId().getProviderName()));
APIUtil.setResourcePermissions(apiProduct.getId().getProviderName(), null, null, thumbPath);
//need to set product resource mappings before updating product, otherwise existing mappings will be lost
List<APIProductResource> resources = apiProvider.getResourcesOfAPIProduct(apiProduct.getId());
apiProduct.setProductResources(resources);
apiProvider.updateAPIProduct(apiProduct);
*/
String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiProductId);
URI uri = new URI(uriString);
FileInfoDTO infoDTO = new FileInfoDTO();
infoDTO.setRelativePath(uriString);
infoDTO.setMediaType(apiImage.getContentType());
return Response.created(uri).entity(infoDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Error while updating API Product : " + apiProductId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving thumbnail location of API Product : " + apiProductId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Aggregations