use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.
the class ImportUtils method checkAPIProductResourcesValid.
/**
* This method checks whether the resources in the API Product are valid.
*
* @param path Location of the extracted folder of the API Product
* @param currentUser The current logged in user
* @param apiProvider API provider
* @param apiProductDto API Product DTO
* @param preserveProvider
* @param organization
* @throws IOException If there is an error while reading an API file
* @throws APIManagementException If failed to get the API Provider of an API,
* or failed when checking the existence of an API
*/
private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider, String organization) throws IOException, APIManagementException {
// Get dependent APIs in the API Product
List<ProductAPIDTO> apis = apiProductDto.getApis();
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();
JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser, ImportExportConstants.TYPE_API);
APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class);
String apiName = apiDto.getName();
String apiVersion = apiDto.getVersion();
String swaggerContent = loadSwaggerFile(apiDirectoryPath);
APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent);
for (ProductAPIDTO apiFromProduct : apis) {
if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils.equals(apiFromProduct.getVersion(), apiVersion)) {
List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources(apiFromProduct.getOperations(), apiUriTemplates);
// dependent APIs inside the directory) check whether those are already inside APIM
if (!invalidApiOperations.isEmpty()) {
// Get the provider of the API if the API is in current user's tenant domain.
API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates());
}
// inside the APIM
if (!invalidApiOperations.isEmpty()) {
throw new APIMgtResourceNotFoundException("Cannot find API resources for some API Product resources.");
}
}
}
}
}
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.
the class PublisherCommonUtils method extractGraphQLOperationList.
/**
* Extract GraphQL Operations from given schema.
*
* @param schema graphQL Schema
* @return the arrayList of APIOperationsDTOextractGraphQLOperationList
*/
public static List<APIOperationsDTO> extractGraphQLOperationList(String schema) {
List<APIOperationsDTO> operationArray = new ArrayList<>();
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) || entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION) || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
APIOperationsDTO operation = new APIOperationsDTO();
operation.setVerb(entry.getKey());
operation.setTarget(fieldDef.getName());
operationArray.add(operation);
}
}
}
return operationArray;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.
the class PublisherCommonUtils method getRemovedProductResources.
/**
* Finds resources that have been removed in the updated API, that are currently reused by API Products.
*
* @param updatedDTO Updated API
* @param existingAPI Existing API
* @return List of removed resources that are reused among API Products
*/
private static List<APIResource> getRemovedProductResources(APIDTO updatedDTO, API existingAPI) {
List<APIOperationsDTO> updatedOperations = updatedDTO.getOperations();
Set<URITemplate> existingUriTemplates = existingAPI.getUriTemplates();
List<APIResource> removedReusedResources = new ArrayList<>();
for (URITemplate existingUriTemplate : existingUriTemplates) {
// If existing URITemplate is used by any API Products
if (!existingUriTemplate.retrieveUsedByProducts().isEmpty()) {
String existingVerb = existingUriTemplate.getHTTPVerb();
String existingPath = existingUriTemplate.getUriTemplate();
boolean isReusedResourceRemoved = true;
for (APIOperationsDTO updatedOperation : updatedOperations) {
String updatedVerb = updatedOperation.getVerb();
String updatedPath = updatedOperation.getTarget();
// Check if existing reused resource is among updated resources
if (existingVerb.equalsIgnoreCase(updatedVerb) && existingPath.equalsIgnoreCase(updatedPath)) {
isReusedResourceRemoved = false;
break;
}
}
// Existing reused resource is not among updated resources
if (isReusedResourceRemoved) {
APIResource removedResource = new APIResource(existingVerb, existingPath);
removedReusedResources.add(removedResource);
}
}
}
return removedReusedResources;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO in project carbon-apimgt by wso2.
the class APIMappingUtil method fromDTOtoAPIProduct.
public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
APIProduct product = new APIProduct();
APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
APIConstants.API_PRODUCT_VERSION);
product.setID(id);
product.setUuid(dto.getId());
product.setDescription(dto.getDescription());
String context = dto.getContext();
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
context = context.startsWith("/") ? context : ("/" + context);
String providerDomain = MultitenantUtils.getTenantDomain(provider);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
// Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
product.setContext(context);
context = checkAndSetVersionParam(context);
product.setContextTemplate(context);
List<String> apiProductTags = dto.getTags();
Set<String> tagsToReturn = new HashSet<>(apiProductTags);
product.addTags(tagsToReturn);
if (dto.isEnableSchemaValidation() != null) {
product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
}
product.setEnableStore(true);
if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
product.setResponseCache(APIConstants.ENABLED);
} else {
product.setResponseCache(APIConstants.DISABLED);
}
if (dto.getCacheTimeout() != null) {
product.setCacheTimeout(dto.getCacheTimeout());
} else {
product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
}
if (dto.getBusinessInformation() != null) {
product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
}
Set<Tier> apiTiers = new HashSet<>();
List<String> tiersFromDTO = dto.getPolicies();
if (dto.getVisibility() != null) {
product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
}
if (dto.getVisibleRoles() != null) {
String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
product.setVisibleRoles(visibleRoles);
}
if (dto.getVisibleTenants() != null) {
String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
product.setVisibleTenants(visibleTenants);
}
List<String> accessControlRoles = dto.getAccessControlRoles();
if (accessControlRoles == null || accessControlRoles.isEmpty()) {
product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
product.setAccessControlRoles("null");
} else {
product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
}
for (String tier : tiersFromDTO) {
apiTiers.add(new Tier(tier));
}
product.setAvailableTiers(apiTiers);
product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
product.setGatewayVendor(dto.getGatewayVendor());
if (dto.getSubscriptionAvailability() != null) {
product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
}
List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
if (additionalProperties != null) {
for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
if (property.isDisplay()) {
product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
} else {
product.addProperty(property.getName(), property.getValue());
}
}
}
if (dto.getSubscriptionAvailableTenants() != null) {
product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
}
String transports = StringUtils.join(dto.getTransport(), ',');
product.setTransports(transports);
List<APIProductResource> productResources = new ArrayList<APIProductResource>();
Set<String> verbResourceCombo = new HashSet<>();
for (ProductAPIDTO res : dto.getApis()) {
List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
}
URITemplate template = new URITemplate();
template.setHTTPVerb(resourceItem.getVerb());
template.setHttpVerbs(resourceItem.getVerb());
template.setResourceURI(resourceItem.getTarget());
template.setUriTemplate(resourceItem.getTarget());
template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
APIProductResource resource = new APIProductResource();
resource.setApiId(res.getApiId());
resource.setUriTemplate(template);
productResources.add(resource);
}
}
Set<Scope> scopes = getScopes(dto);
product.setScopes(scopes);
APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
CORSConfiguration corsConfiguration;
if (apiCorsConfigurationDTO != null) {
corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
} else {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
product.setCorsConfiguration(corsConfiguration);
product.setProductResources(productResources);
product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
product.setAuthorizationHeader(dto.getAuthorizationHeader());
// attach api categories to API model
setAPICategoriesToModel(dto, product, provider);
return product;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO 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;
}
Aggregations