Search in sources :

Example 56 with URITemplate

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

the class OASTestBase method testGenerateAPIDefinition2.

public void testGenerateAPIDefinition2(APIDefinition parser, String content, OASParserEvaluator evaluator) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String equalNoOfResources = jsonObject.getJSONObject("equalNoOfResources").toString();
    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petGet, petPost, itemGet, itemPost)));
    String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResources);
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    Set<URITemplate> uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(4, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
    Assert.assertTrue(uriTemplates.contains(petPost));
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
    Set<Scope> scopes = parser.getScopes(definition);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
    // Remove operation and path from API object
    String extraResourcesInDefinition = jsonObject.getJSONObject("extraResourcesInDefinition").toString();
    api.setUriTemplates(new HashSet<>(Arrays.asList(itemGet, itemPost)));
    definition = parser.generateAPIDefinition(new SwaggerData(api), extraResourcesInDefinition);
    response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(2, uriTemplates.size());
    // assert generated paths
    if (evaluator != null) {
        evaluator.eval(definition);
    }
    Iterator iterator = uriTemplates.iterator();
    while (iterator.hasNext()) {
        URITemplate element = (URITemplate) iterator.next();
        if ("/pets".equalsIgnoreCase(element.getUriTemplate())) {
            Assert.fail("Removed paths from API operation should not present.");
        }
        if ("/items".equalsIgnoreCase(element.getUriTemplate()) && "PUT".equalsIgnoreCase(element.getHTTPVerb())) {
            Assert.fail("Removed item from API operation should not present.");
        }
    }
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
    // Add operation and path to API object
    String lessResourcesInDefinition = jsonObject.getJSONObject("lessResourcesInDefinition").toString();
    api.setUriTemplates(new HashSet<>(Arrays.asList(petGet, petPost, itemGet, itemPost)));
    definition = parser.generateAPIDefinition(new SwaggerData(api), lessResourcesInDefinition);
    response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(4, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
    Assert.assertTrue(uriTemplates.contains(petPost));
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
}
Also used : JSONObject(org.json.JSONObject) Scope(org.wso2.carbon.apimgt.api.model.Scope) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Iterator(java.util.Iterator) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 57 with URITemplate

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

the class APIMgtDAOTest method getUriTemplate.

private URITemplate getUriTemplate(String resourceString, String httpVerb, String authType, String scope, String throtlingTier) {
    URITemplate uriTemplate = new URITemplate();
    uriTemplate.setUriTemplate(resourceString);
    uriTemplate.setHTTPVerb(httpVerb);
    uriTemplate.setThrottlingTier(throtlingTier);
    uriTemplate.setAuthType(authType);
    uriTemplate.setMediationScript("abcd defgh fff");
    if (scope != null) {
        Scope scope1 = new Scope();
        scope1.setId("0");
        scope1.setDescription("");
        scope1.setKey(scope);
        scope1.setName(scope);
        scope1.setRoles("admin");
        uriTemplate.setScope(scope1);
        uriTemplate.setScopes(scope1);
    }
    return uriTemplate;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 58 with URITemplate

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

the class RecommenderDetailsExtractor method publishAPIDetails.

@Override
public void publishAPIDetails(API api, String tenantDomain) throws IOException {
    String apiName = api.getId().getApiName();
    String apiStatus = api.getStatus();
    String apiId = api.getUUID();
    if (apiStatus == null) {
        apiStatus = APIConstants.DELETED_STATUS;
    }
    if (apiStatus.equals(APIConstants.PUBLISHED_STATUS) && APIConstants.ADD_API.equals(publishingDetailType)) {
        String apiDescription = api.getDescription();
        String apiContext = api.getContext();
        String apiTags = api.getTags().toString();
        Set<URITemplate> uriTemplates = api.getUriTemplates();
        JSONObject swaggerDef = null;
        if (api.getSwaggerDefinition() != null) {
            swaggerDef = new JSONObject(api.getSwaggerDefinition());
        }
        JSONArray resourceArray = new JSONArray();
        JSONObject resourceObj;
        for (URITemplate uriTemplate : uriTemplates) {
            resourceObj = new JSONObject();
            String resource = uriTemplate.getUriTemplate();
            String resourceMethod = uriTemplate.getHTTPVerb();
            resourceObj.put("resource", resource);
            if (swaggerDef != null) {
                String summary = getDescriptionFromSwagger(swaggerDef, resource, resourceMethod, "summary");
                String description = getDescriptionFromSwagger(swaggerDef, resource, resourceMethod, "description");
                resourceObj.put("summary", summary);
                resourceObj.put("description", description);
            }
            resourceArray.put(resourceObj);
        }
        JSONObject obj = new JSONObject();
        obj.put("api_id", apiId);
        obj.put("api_name", apiName);
        obj.put("description", apiDescription);
        obj.put("context", apiContext);
        obj.put("tenant", tenantDomain);
        obj.put("tags", apiTags);
        obj.put("resources", resourceArray);
        JSONObject payload = new JSONObject();
        payload.put("action", APIConstants.ADD_API);
        payload.put("payload", obj);
        publishEvent(payload.toString());
        log.info("Add API event for " + apiName + " API was published to the recommendation server");
    } else {
        JSONObject obj = new JSONObject();
        obj.put("api_name", apiName);
        obj.put("tenant", tenantDomain);
        JSONObject payload = new JSONObject();
        payload.put(APIConstants.ACTION_STRING, APIConstants.DELETE_API);
        payload.put(APIConstants.PAYLOAD_STRING, obj);
        publishEvent(payload.toString());
        log.info("Delete API event for " + apiName + " API was published to the recommendation server");
    }
}
Also used : JSONObject(org.json.JSONObject) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) JSONArray(org.json.JSONArray)

Example 59 with URITemplate

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

the class APIMappingUtil method setOperationPoliciesToOperationsDTO.

/**
 * Reads the operationPolicies from the API object passed in, and sets them back to the API Operations DTO
 *
 * @param api               API object
 * @param apiOperationsDTO  List of API Operations DTO
 */
private static void setOperationPoliciesToOperationsDTO(API api, List<APIOperationsDTO> apiOperationsDTO) {
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    Map<String, URITemplate> uriTemplateMap = new HashMap<>();
    for (URITemplate uriTemplate : uriTemplates) {
        String key = uriTemplate.getUriTemplate() + ":" + uriTemplate.getHTTPVerb();
        uriTemplateMap.put(key, uriTemplate);
    }
    for (APIOperationsDTO operationsDTO : apiOperationsDTO) {
        String key = operationsDTO.getTarget() + ":" + operationsDTO.getVerb();
        List<OperationPolicy> operationPolicies = uriTemplateMap.get(key).getOperationPolicies();
        if (!operationPolicies.isEmpty()) {
            operationsDTO.setOperationPolicies(OperationPolicyMappingUtil.fromOperationPolicyListToDTO(operationPolicies));
        }
    }
}
Also used : HashMap(java.util.HashMap) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO)

Example 60 with URITemplate

use of org.wso2.carbon.apimgt.api.model.URITemplate 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;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) 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