use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO in project carbon-apimgt by wso2.
the class ApiProductsApiServiceImpl method getAPIProductByID.
private APIProductDTO getAPIProductByID(String apiProductId, APIProvider apiProvider) {
try {
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
APIProduct api = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
return APIMappingUtil.fromAPIProducttoDTO(api);
} catch (APIManagementException e) {
// to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("User is not authorized to access the API Product", e, log);
} else {
String errorMessage = "Error while retrieving API Product : " + apiProductId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPIProducttoDTO.
public static APIProductDTO fromAPIProducttoDTO(APIProduct product) throws APIManagementException {
APIProductDTO productDto = new APIProductDTO();
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
productDto.setName(product.getId().getName());
productDto.setProvider(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
productDto.setId(product.getUuid());
productDto.setContext(product.getContext());
productDto.setDescription(product.getDescription());
productDto.setApiType(APIProductDTO.ApiTypeEnum.fromValue(APIConstants.AuditLogConstants.API_PRODUCT));
productDto.setAuthorizationHeader(product.getAuthorizationHeader());
productDto.setGatewayVendor(product.getGatewayVendor());
Set<String> apiTags = product.getTags();
List<String> tagsToReturn = new ArrayList<>(apiTags);
productDto.setTags(tagsToReturn);
productDto.setEnableSchemaValidation(product.isEnabledSchemaValidation());
productDto.setIsRevision(product.isRevision());
productDto.setRevisionedApiProductId(product.getRevisionedApiProductId());
productDto.setRevisionId(product.getRevisionId());
if (APIConstants.ENABLED.equals(product.getResponseCache())) {
productDto.setResponseCachingEnabled(Boolean.TRUE);
} else {
productDto.setResponseCachingEnabled(Boolean.FALSE);
}
productDto.setCacheTimeout(product.getCacheTimeout());
APIProductBusinessInformationDTO businessInformation = new APIProductBusinessInformationDTO();
businessInformation.setBusinessOwner(product.getBusinessOwner());
businessInformation.setBusinessOwnerEmail(product.getBusinessOwnerEmail());
businessInformation.setTechnicalOwner(product.getTechnicalOwner());
businessInformation.setTechnicalOwnerEmail(product.getTechnicalOwnerEmail());
productDto.setBusinessInformation(businessInformation);
APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
CORSConfiguration corsConfiguration = product.getCorsConfiguration();
if (corsConfiguration == null) {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
productDto.setCorsConfiguration(apiCorsConfigurationDTO);
productDto.setState(StateEnum.valueOf(product.getState()));
productDto.setWorkflowStatus(product.getWorkflowStatus());
// Aggregate API resources to each relevant API.
Map<String, ProductAPIDTO> aggregatedAPIs = new HashMap<String, ProductAPIDTO>();
List<APIProductResource> resources = product.getProductResources();
for (APIProductResource apiProductResource : resources) {
String uuid = apiProductResource.getApiId();
if (aggregatedAPIs.containsKey(uuid)) {
ProductAPIDTO productAPI = aggregatedAPIs.get(uuid);
URITemplate template = apiProductResource.getUriTemplate();
List<APIOperationsDTO> operations = productAPI.getOperations();
APIOperationsDTO operation = getOperationFromURITemplate(template);
operations.add(operation);
} else {
ProductAPIDTO productAPI = new ProductAPIDTO();
productAPI.setApiId(uuid);
productAPI.setName(apiProductResource.getApiName());
productAPI.setVersion(apiProductResource.getApiIdentifier().getVersion());
List<APIOperationsDTO> operations = new ArrayList<APIOperationsDTO>();
URITemplate template = apiProductResource.getUriTemplate();
APIOperationsDTO operation = getOperationFromURITemplate(template);
operations.add(operation);
productAPI.setOperations(operations);
aggregatedAPIs.put(uuid, productAPI);
}
}
productDto.setApis(new ArrayList<>(aggregatedAPIs.values()));
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
String apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(product.getId(), tenantDomain);
List<ScopeDTO> scopeDTOS = getScopesFromSwagger(apiSwaggerDefinition);
productDto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS));
String subscriptionAvailability = product.getSubscriptionAvailability();
if (subscriptionAvailability != null) {
productDto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPIProducttoDTO(subscriptionAvailability));
}
if (product.getSubscriptionAvailableTenants() != null) {
productDto.setSubscriptionAvailableTenants(Arrays.asList(product.getSubscriptionAvailableTenants().split(",")));
}
Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = product.getAvailableTiers();
List<String> tiersToReturn = new ArrayList<>();
for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
tiersToReturn.add(tier.getName());
}
productDto.setPolicies(tiersToReturn);
productDto.setApiThrottlingPolicy(product.getProductLevelPolicy());
if (product.getVisibility() != null) {
productDto.setVisibility(mapVisibilityFromAPIProducttoDTO(product.getVisibility()));
}
if (product.getVisibleRoles() != null) {
productDto.setVisibleRoles(Arrays.asList(product.getVisibleRoles().split(",")));
}
if (product.getVisibleTenants() != null) {
productDto.setVisibleTenants(Arrays.asList(product.getVisibleTenants().split(",")));
}
productDto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(product.getAccessControl()) ? APIProductDTO.AccessControlEnum.RESTRICTED : APIProductDTO.AccessControlEnum.NONE);
if (product.getAccessControlRoles() != null) {
productDto.setAccessControlRoles(Arrays.asList(product.getAccessControlRoles().split(",")));
}
if (StringUtils.isEmpty(product.getTransports())) {
List<String> transports = new ArrayList<>();
transports.add(APIConstants.HTTPS_PROTOCOL);
productDto.setTransport(transports);
} else {
productDto.setTransport(Arrays.asList(product.getTransports().split(",")));
}
if (product.getAdditionalProperties() != null) {
JSONObject additionalProperties = product.getAdditionalProperties();
List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
for (Object propertyKey : additionalProperties.keySet()) {
APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
String key = (String) propertyKey;
int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
if (index > 0) {
additionalPropertiesDTO.setName(key.substring(0, index));
apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
additionalPropertiesDTO.setDisplay(true);
} else {
additionalPropertiesDTO.setName(key);
apiInfoAdditionalPropertiesMapDTO.setName(key);
additionalPropertiesDTO.setDisplay(false);
}
apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
additionalPropertiesList.add(additionalPropertiesDTO);
}
productDto.setAdditionalPropertiesMap(additionalPropertiesMap);
productDto.setAdditionalProperties(additionalPropertiesList);
}
if (product.getApiSecurity() != null) {
productDto.setSecurityScheme(Arrays.asList(product.getApiSecurity().split(",")));
}
List<APICategory> apiCategories = product.getApiCategories();
List<String> categoryNameList = new ArrayList<>();
if (apiCategories != null && !apiCategories.isEmpty()) {
for (APICategory category : apiCategories) {
categoryNameList.add(category.getName());
}
}
productDto.setCategories(categoryNameList);
if (null != product.getLastUpdated()) {
Date lastUpdateDate = product.getLastUpdated();
Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
productDto.setLastUpdatedTime(String.valueOf(timeStamp));
}
if (null != product.getCreatedTime()) {
Date createdTime = product.getCreatedTime();
Timestamp timeStamp = new Timestamp(createdTime.getTime());
productDto.setCreatedTime(String.valueOf(timeStamp));
}
return productDto;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO in project carbon-apimgt by wso2.
the class ImportUtils method updateApiUuidInApiProduct.
/**
* This method updates the UUID of the dependent API in an API Product.
*
* @param apiProductDto API Product DTO
* @param importedApi Imported API
*/
private static APIProductDTO updateApiUuidInApiProduct(APIProductDTO apiProductDto, API importedApi) {
APIIdentifier importedApiIdentifier = importedApi.getId();
List<ProductAPIDTO> apis = apiProductDto.getApis();
for (ProductAPIDTO api : apis) {
if (StringUtils.equals(api.getName(), importedApiIdentifier.getName()) && StringUtils.equals(api.getVersion(), importedApiIdentifier.getVersion())) {
api.setApiId(importedApi.getUuid());
break;
}
}
return apiProductDto;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO in project carbon-apimgt by wso2.
the class ImportUtils method importDependentAPIs.
/**
* This method imports dependent APIs of the API Product.
*
* @param path Location of the extracted folder of the API Product
* @param currentUser The current logged in user
* @param isDefaultProviderAllowed Decision to keep or replace the provider
* @param apiProvider API provider
* @param overwriteAPIs Whether to overwrite the APIs or not
* @param apiProductDto API Product DTO
* @param tokenScopes Scopes of the token
* @param organization Organization Identifier
* @return Modified API Product DTO with the correct API UUIDs
* @throws IOException If there is an error while reading an API file
* @throws APIImportExportException If there is an error in importing an API
* @throws APIManagementException If failed to get the API Provider of an API, or failed when
* checking the existence of an API
*/
private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, boolean overwriteAPIs, Boolean rotateRevision, APIProductDTO apiProductDto, String[] tokenScopes, String organization) throws IOException, APIManagementException {
JsonObject dependentAPIParamsConfigObject = null;
// Retrieve the dependent APIs param configurations from the params file of the API Product
JsonObject dependentAPIsParams = APIControllerUtil.getDependentAPIsParams(path);
String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
File apisDirectory = new File(apisDirectoryPath);
File[] apisDirectoryListing = apisDirectory.listFiles();
if (apisDirectoryListing != null) {
for (File apiDirectory : apisDirectoryListing) {
String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
// API in the API directory will be retrieved if available
if (dependentAPIsParams != null) {
dependentAPIParamsConfigObject = APIControllerUtil.getDependentAPIParams(dependentAPIsParams, apiDirectory.getName());
// If the "certificates" directory is specified, copy it inside Deployment directory of the
// dependent API since there may be certificates required for APIs
String deploymentCertificatesDirectoryPath = path + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
if (CommonUtil.checkFileExistence(deploymentCertificatesDirectoryPath)) {
try {
CommonUtil.copyDirectory(deploymentCertificatesDirectoryPath, apiDirectoryPath + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY);
} catch (APIImportExportException e) {
throw new APIManagementException("Error while copying the directory " + deploymentCertificatesDirectoryPath, e);
}
}
}
JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser, ImportExportConstants.TYPE_API);
APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class);
API importedApi = null;
String apiName = apiDtoToImport.getName();
String apiVersion = apiDtoToImport.getVersion();
if (isDefaultProviderAllowed) {
APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion);
// Checking whether the API exists
if (apiProvider.isAPIAvailable(apiIdentifier, organization)) {
// otherwise do not update the API. (Just skip it)
if (Boolean.TRUE.equals(overwriteAPIs)) {
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
} else {
// If the API is not already imported, import it
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
} else {
// Retrieve the current tenant domain of the logged in user
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser));
// Get the provider of the API if the API is in current user's tenant domain.
String apiProviderInCurrentTenantDomain = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain);
if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) {
// If there is no API in the current tenant domain (which means the provider name is blank)
// then the API should be imported freshly
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
} else {
// otherwise do not import/update the API. (Just skip it)
if (Boolean.TRUE.equals(overwriteAPIs)) {
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
}
}
if (importedApi == null) {
// Retrieve the API from the environment (This happens when you have not specified
// the overwrite flag, so that we should retrieve the API from inside)
importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
}
updateApiUuidInApiProduct(apiProductDto, importedApi);
}
} else {
String msg = "No dependent APIs supplied. Continuing ...";
log.info(msg);
}
return apiProductDto;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO 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