Search in sources :

Example 76 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate 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;
}
Also used : APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList)

Example 77 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.

the class PublisherCommonUtils method updateApi.

/**
 * Update an API.
 *
 * @param originalAPI    Existing API
 * @param apiDtoToUpdate New API DTO to update
 * @param apiProvider    API Provider
 * @param tokenScopes    Scopes of the token
 * @throws ParseException         If an error occurs while parsing the endpoint configuration
 * @throws CryptoException        If an error occurs while encrypting the secret key of API
 * @throws APIManagementException If an error occurs while updating the API
 * @throws FaultGatewaysException If an error occurs while updating manage of an existing API
 */
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
    APIIdentifier apiIdentifier = originalAPI.getId();
    // Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
    if (tokenScopes == null) {
        throw new APIManagementException("Error occurred while updating the  API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
    }
    boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
    boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
    Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
    boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
    JSONParser parser = new JSONParser();
    String oldEndpointConfigString = originalAPI.getEndpointConfig();
    JSONObject oldEndpointConfig = null;
    if (StringUtils.isNotBlank(oldEndpointConfigString)) {
        oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
    }
    String oldProductionApiSecret = null;
    String oldSandboxApiSecret = null;
    if (oldEndpointConfig != null) {
        if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
            JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
            if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
                JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
                    oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                }
            }
            if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
                JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
                    oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                }
            }
        }
    }
    Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
    // AWS Lambda: secret key encryption while updating the API
    if (apiDtoToUpdate.getEndpointConfig() != null) {
        if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
            String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            if (!StringUtils.isEmpty(secretKey)) {
                if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
                    String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
                    endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                    apiDtoToUpdate.setEndpointConfig(endpointConfig);
                } else {
                    JSONParser jsonParser = new JSONParser();
                    JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
                    String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
                    endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                    apiDtoToUpdate.setEndpointConfig(endpointConfig);
                }
            }
        }
    }
    if (!hasClassLevelScope) {
        // Validate per-field scopes
        apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
    }
    // API Name change not allowed if OnPrem
    if (APIUtil.isOnPremResolver()) {
        apiDtoToUpdate.setName(apiIdentifier.getApiName());
    }
    apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
    apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
    apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
    apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
    apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
    List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
    if (!removedProductResources.isEmpty()) {
        throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
    }
    // Validate API Security
    List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
    // validation for tiers
    List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
    String originalStatus = originalAPI.getStatus();
    if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
        if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
            throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
        }
    }
    if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
        // 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);
        }
    }
    if (apiDtoToUpdate.getAccessControlRoles() != null) {
        String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (apiDtoToUpdate.getVisibleRoles() != null) {
        String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (apiDtoToUpdate.getAdditionalProperties() != null) {
        String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
        }
    }
    // Validate if resources are empty
    if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
    if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
        apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
    }
    apiToUpdate.setUUID(originalAPI.getUUID());
    apiToUpdate.setOrganization(originalAPI.getOrganization());
    validateScopes(apiToUpdate);
    apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
    if (apiDtoToUpdate.getKeyManagers() instanceof List) {
        apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
    } else {
        apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    }
    if (!isAsyncAPI) {
        String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
        APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
        SwaggerData swaggerData = new SwaggerData(apiToUpdate);
        String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
        apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
        if (!isGraphql) {
            Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
            // set operation policies from the original API Payload
            Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
            Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
            for (URITemplate uriTemplate : uriTemplatesFromPayload) {
                if (!uriTemplate.getOperationPolicies().isEmpty()) {
                    String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
                    operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
                }
            }
            for (URITemplate uriTemplate : uriTemplates) {
                String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
                if (operationPoliciesPerURITemplate.containsKey(key)) {
                    uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
                }
            }
            apiToUpdate.setUriTemplates(uriTemplates);
        }
    } else {
        String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
        apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
    }
    apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
    // validate API categories
    List<APICategory> apiCategories = apiToUpdate.getApiCategories();
    List<APICategory> apiCategoriesList = new ArrayList<>();
    for (APICategory category : apiCategories) {
        category.setOrganization(originalAPI.getOrganization());
        apiCategoriesList.add(category);
    }
    apiToUpdate.setApiCategories(apiCategoriesList);
    if (apiCategoriesList.size() > 0) {
        if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
            throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
        }
    }
    apiToUpdate.setOrganization(originalAPI.getOrganization());
    apiProvider.updateAPI(apiToUpdate, originalAPI);
    return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) List(java.util.List) ArrayList(java.util.ArrayList) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) JSONObject(org.json.simple.JSONObject) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) JSONParser(org.json.simple.parser.JSONParser) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 78 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate 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;
}
Also used : AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdvertiseInfoDTO) HashMap(java.util.HashMap) APITiersDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APITiersDTO) ArrayList(java.util.ArrayList) APIAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIAdditionalPropertiesDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationInfoDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) ScopeInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ScopeInfoDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIMonetizationAttributesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)

Example 79 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.

the class ApiDAOImpl method addUrlMappings.

private void addUrlMappings(Connection connection, Collection<UriTemplate> uriTemplates, String apiID) throws SQLException {
    final String query = "INSERT INTO AM_API_OPERATION_MAPPING (OPERATION_ID,API_ID, HTTP_METHOD, URL_PATTERN, " + "AUTH_SCHEME, API_POLICY_ID) VALUES (?,?,?,?,?,?)";
    try (PreparedStatement statement = connection.prepareStatement(query)) {
        for (UriTemplate uriTemplate : uriTemplates) {
            statement.setString(1, uriTemplate.getTemplateId());
            statement.setString(2, apiID);
            statement.setString(3, uriTemplate.getHttpVerb());
            statement.setString(4, uriTemplate.getUriTemplate());
            statement.setString(5, uriTemplate.getAuthType());
            statement.setString(6, uriTemplate.getPolicy().getUuid());
            statement.addBatch();
        }
        statement.executeBatch();
        for (UriTemplate uriTemplate : uriTemplates) {
            addEndPointsForOperation(connection, apiID, uriTemplate.getTemplateId(), uriTemplate.getEndpoint());
        }
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate)

Example 80 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.

the class ApiDAOImpl method deleteEndPointsForOperation.

private void deleteEndPointsForOperation(Connection connection, String apiId) throws SQLException, IOException {
    final String query = "DELETE FROM AM_API_RESOURCE_ENDPOINT WHERE API_ID = ?";
    Set<String> endpoints = new HashSet<>();
    Map<String, UriTemplate> uriTemplates = getUriTemplates(connection, apiId);
    for (Map.Entry<String, UriTemplate> uriTemplate : uriTemplates.entrySet()) {
        Map<String, Endpoint> apiEndPoints = getEndPointsForOperation(connection, apiId, uriTemplate.getValue().getTemplateId());
        for (Map.Entry<String, Endpoint> apiEndpoint : apiEndPoints.entrySet()) {
            Endpoint endpoint = apiEndpoint.getValue();
            if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(endpoint.getApplicableLevel())) {
                endpoints.add(endpoint.getId());
            }
        }
    }
    try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
        preparedStatement.setString(1, apiId);
        preparedStatement.execute();
        for (String endpointId : endpoints) {
            if (!isEndpointAssociated(connection, endpointId)) {
                deleteEndpoint(connection, endpointId);
            }
        }
    }
}
Also used : Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) PreparedStatement(java.sql.PreparedStatement) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)122 HashMap (java.util.HashMap)71 ArrayList (java.util.ArrayList)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)42 Scope (org.wso2.carbon.apimgt.api.model.Scope)41 API (org.wso2.carbon.apimgt.api.model.API)38 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 HashSet (java.util.HashSet)36 LinkedHashSet (java.util.LinkedHashSet)28 PreparedStatement (java.sql.PreparedStatement)25 ResultSet (java.sql.ResultSet)23 API (org.wso2.carbon.apimgt.core.models.API)22 Map (java.util.Map)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 Connection (java.sql.Connection)20 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)20 LinkedHashMap (java.util.LinkedHashMap)19 List (java.util.List)19 SQLException (java.sql.SQLException)16