use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class ImportUtils method importSubscriptions.
/**
* Import and add subscriptions of a particular application for the available APIs and API products
*
* @param subscribedAPIs Subscribed APIs
* @param userId Username of the subscriber
* @param application Application
* @param update Whether to update the application or not
* @param apiConsumer API Consumer
* @param organization Organization
* @return a list of APIIdentifiers of the skipped subscriptions
* @throws APIManagementException if an error occurs while importing and adding subscriptions
* @throws UserStoreException if an error occurs while checking whether the tenant domain exists
*/
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
List<APIIdentifier> skippedAPIList = new ArrayList<>();
for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
APIIdentifier apiIdentifier = subscribedAPI.getApiId();
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
String name = apiIdentifier.getApiName();
String version = apiIdentifier.getVersion();
// Creating a solr compatible search query, here we will execute a search query without wildcard *s
StringBuilder searchQuery = new StringBuilder();
String[] searchCriteria = { name, "version:" + version };
for (int i = 0; i < searchCriteria.length; i++) {
if (i == 0) {
searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
} else {
searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
}
}
Map matchedAPIs;
matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
if (apiSet != null && !apiSet.isEmpty()) {
Object type = apiSet.iterator().next();
ApiTypeWrapper apiTypeWrapper = null;
String apiOrApiProductUuid;
// Check whether the object is ApiProduct
if (isApiProduct(type)) {
APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
} else {
API api = (API) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
}
apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
// Tier of the imported subscription
String targetTier = subscribedAPI.getThrottlingPolicy();
// Checking whether the target tier is available
if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
apiTypeWrapper.setTier(targetTier);
// It will throw an error if subscriber already exists
if (update == null || !update) {
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
} else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
// on update skip subscriptions that already exists
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
}
} else {
log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
}
return skippedAPIList;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class PublisherCommonUtils method prepareToCreateAPIByDTO.
/**
* Prepares the API Model object to be created using the DTO object.
*
* @param body APIDTO of the API
* @param apiProvider API Provider
* @param username Username
* @param organization Organization Identifier
* @return API object to be created
* @throws APIManagementException Error while creating the API
*/
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
String context = body.getContext();
// Make sure context starts with "/". ex: /pizza
context = context.startsWith("/") ? context : ("/" + context);
if (body.getAccessControlRoles() != null) {
String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (body.getAdditionalProperties() != null) {
String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
}
}
if (body.getContext() == null) {
throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
} else if (body.getContext().endsWith("/")) {
throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
}
if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
}
if (body.getAuthorizationHeader() == null) {
body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
}
if (body.getAuthorizationHeader() == null) {
body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
}
if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
}
if (body.getVisibleRoles() != null) {
String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
// Get all existing versions of api been adding
List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
if (apiVersions.size() > 0) {
// If any previous version exists
for (String version : apiVersions) {
if (version.equalsIgnoreCase(body.getVersion())) {
// If version already exists
if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
} else {
throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
}
}
}
} else {
// If no any previous version exists
if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
}
}
// Check if the user has admin permission before applying a different provider than the current user
String provider = body.getProvider();
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 {
if (!APIUtil.isUserExist(provider)) {
throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
}
} else {
// Set username in case provider is null or empty
provider = username;
}
List<String> tiersFromDTO = body.getPolicies();
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
}
API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
// only allow CREATED as the stating state for the new api if not status is PROTOTYPED
if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
apiToAdd.setStatus(APIConstants.CREATED);
}
if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
// we are setting the api owner as the logged in user until we support checking admin privileges and
// assigning the owner as a different user
apiToAdd.setApiOwner(provider);
}
if (body.getKeyManagers() instanceof List) {
apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
} else if (body.getKeyManagers() == null) {
apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
} else {
throw new APIManagementException("KeyManagers value need to be an array");
}
// Set default gatewayVendor
if (body.getGatewayVendor() == null) {
apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
}
apiToAdd.setOrganization(organization);
return apiToAdd;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class PublisherCommonUtilsTest method testGetInvalidTierNames.
@Test
public void testGetInvalidTierNames() throws Exception {
List<String> currentTiers = Arrays.asList(new String[] { "Unlimitted", "Platinum", "gold" });
Tier mockTier = Mockito.mock(Tier.class);
Tier tier1 = new Tier("Gold");
Tier tier2 = new Tier("Unlimitted");
Tier tier3 = new Tier("Silver");
Set<Tier> allTiers = new HashSet<Tier>();
allTiers.add(tier1);
allTiers.add(tier2);
allTiers.add(tier3);
PowerMockito.whenNew(Tier.class).withAnyArguments().thenReturn(mockTier);
Mockito.when(mockTier.getName()).thenReturn("Unlimitted");
List<String> expectedInvalidTier = Arrays.asList(new String[] { "Platinum", "gold" });
Assert.assertEquals(PublisherCommonUtils.getInvalidTierNames(allTiers, currentTiers), expectedInvalidTier);
}
use of org.wso2.carbon.apimgt.api.model.Tier 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.api.model.Tier in project carbon-apimgt by wso2.
the class ThrottlingPolicyMappingUtil method setPaginationParams.
/**
* Sets pagination urls for a ThrottlingPolicyListDTO object given pagination parameters and url parameters.
*
* @param throttlingPolicyListDTO a ThrottlingPolicyListDTO object
* @param tierLevel tier level (api/application or resource)
* @param limit max number of objects returned
* @param offset starting index
* @param size max offset
*/
public static void setPaginationParams(ThrottlingPolicyListDTO throttlingPolicyListDTO, String tierLevel, int limit, int offset, int size) {
String paginatedPrevious = "";
String paginatedNext = "";
Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
paginatedPrevious = RestApiCommonUtil.getTiersPaginatedURL(tierLevel, paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT));
}
if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
paginatedNext = RestApiCommonUtil.getTiersPaginatedURL(tierLevel, paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT));
}
PaginationDTO paginationDTO = CommonMappingUtil.getPaginationDTO(limit, offset, size, paginatedNext, paginatedPrevious);
throttlingPolicyListDTO.setPagination(paginationDTO);
}
Aggregations