Search in sources :

Example 96 with URITemplate

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

the class ApiDAOImplIT method addAPIWithGivenData.

/**
 * This method adds an API with given information
 *
 * @param apiName                API name
 * @param apiVersion             API version
 * @param apiContext             API context
 * @param apiProvider            API provider
 * @param apiVisibility          API visibility
 * @param visibleRoles           roles that are eligible to consume the API
 * @param initialLifecycleStatus initial lifecycle status
 * @param description            API description
 * @param tags                   tag list for the API
 * @param uriTemplates           URI templates, i.e - resources
 * @param finalLifecycleStatus   final lifecycle status
 * @throws APIMgtDAOException if it fails to add the API
 */
private void addAPIWithGivenData(String apiName, String apiVersion, String apiContext, String apiProvider, API.Visibility apiVisibility, Set<String> visibleRoles, String initialLifecycleStatus, String description, Set<String> tags, Map<String, UriTemplate> uriTemplates, String finalLifecycleStatus) throws APIMgtDAOException {
    API.APIBuilder builder;
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    builder = SampleTestObjectCreator.createCustomAPI(apiName, apiVersion, apiContext);
    builder.provider(apiProvider);
    builder.createdBy(apiProvider);
    builder.visibility(apiVisibility);
    // visible roles should be added for restricted APIs
    if (apiVisibility != null && API.Visibility.RESTRICTED.toString().equalsIgnoreCase(apiVisibility.toString())) {
        builder.visibleRoles(visibleRoles);
    }
    builder.lifeCycleStatus(initialLifecycleStatus);
    builder.description(description);
    builder.tags(tags);
    builder.uriTemplates(uriTemplates);
    builder.endpoint(Collections.emptyMap());
    API api = builder.build();
    apiDAO.addAPI(api);
    apiDAO.changeLifeCycleStatus(api.getId(), finalLifecycleStatus);
}
Also used : CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO)

Example 97 with URITemplate

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

the class ApiDAOImplIT method testGetResourcesOfApi.

@Test
public void testGetResourcesOfApi() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI();
    PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
    API api = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api);
    List<UriTemplate> uriTemplateList = apiDAO.getResourcesOfApi(api.getContext(), api.getVersion());
    for (Map.Entry<String, UriTemplate> entry : api.getUriTemplates().entrySet()) {
        UriTemplate uriTemplate = entry.getValue();
        for (UriTemplate v : uriTemplateList) {
            if (v.getTemplateId().equals(uriTemplate.getTemplateId())) {
                Assert.assertEquals(uriTemplate.getAuthType(), v.getAuthType(), TestUtil.printDiff(uriTemplate.getAuthType(), v.getAuthType()));
                Assert.assertEquals(uriTemplate.getHttpVerb(), v.getHttpVerb(), TestUtil.printDiff(uriTemplate.getHttpVerb(), v.getHttpVerb()));
                Assert.assertEquals(uriTemplate.getUriTemplate(), v.getUriTemplate(), TestUtil.printDiff(uriTemplate.getUriTemplate(), v.getUriTemplate()));
                Assert.assertEquals(uriTemplate.getPolicy().getPolicyName(), policyDAO.getApiPolicyByUuid(v.getPolicy().getUuid()).getPolicyName(), TestUtil.printDiff(uriTemplate.getPolicy().getPolicyName(), policyDAO.getApiPolicyByUuid(v.getPolicy().getUuid()).getPolicyName()));
            }
        }
    }
}
Also used : CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) HashMap(java.util.HashMap) Map(java.util.Map) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

Example 98 with URITemplate

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

the class ApiDAOImplIT method createAPIsAndGetIDsOfAddedAPIs.

/**
 * This method creates few APIs and returns the ID list of those APIs
 *
 * @return the ID list of added APIs
 * @throws APIMgtDAOException if it fails to creates APIs
 */
private List<String> createAPIsAndGetIDsOfAddedAPIs() throws APIMgtDAOException {
    Set<String> visibleRoles = new HashSet<>();
    Set<String> apiTags = new HashSet<>();
    List<String> apiIDList = new ArrayList<>();
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    Map<String, UriTemplate> uriTemplateMap;
    // Construct an API which has public visibility
    apiTags.add("Car");
    apiTags.add("Van");
    uriTemplateMap = getUriTemplateMap(new String[] { "/toyota", "/nissan" });
    addAPIWithGivenData("PublicAPI", "1.2.3", "PublicContext", "Paul", API.Visibility.PUBLIC, null, APIStatus.CREATED.getStatus(), "This is a public API, visible to all.", apiTags, uriTemplateMap, APIStatus.PUBLISHED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Paul").get(0).getId());
    // Construct an API which is visible to manager role only
    apiTags.add("Pizza");
    apiTags.add("Cake");
    uriTemplateMap = getUriTemplateMap(new String[] { "/pizzahut", "/dominos" });
    visibleRoles.add(MANAGER_ROLE);
    addAPIWithGivenData("ManagerOnlyAPI", "2.3.4", "managerContext", "Mark", API.Visibility.RESTRICTED, visibleRoles, APIStatus.CREATED.getStatus(), "Users with manager role can view this API.", apiTags, uriTemplateMap, APIStatus.PUBLISHED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Mark").get(0).getId());
    // Construct an API which is visible to admin and manager roles
    apiTags.add("Java");
    uriTemplateMap = getUriTemplateMap(new String[] { "/desktop", "/laptop", "nikoncam" });
    visibleRoles.add(ADMIN);
    visibleRoles.add(MANAGER_ROLE);
    addAPIWithGivenData("AdminManagerAPI", "3.4.5", "adminManager", "Alex", API.Visibility.RESTRICTED, visibleRoles, APIStatus.CREATED.getStatus(), "Admin and manager can see this API.", apiTags, uriTemplateMap, APIStatus.PUBLISHED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Alex").get(0).getId());
    // Construct an API in created state, this should not be shown in store
    apiTags.add("Movie");
    apiTags.add("TV");
    uriTemplateMap = getUriTemplateMap(new String[] { "/cnn", "/bbc" });
    addAPIWithGivenData("CreatedStateAPI", "4.5.6", "createdContext", "Colin", API.Visibility.PUBLIC, null, APIStatus.CREATED.getStatus(), "This API is in created state. Should not be shown in store.", apiTags, uriTemplateMap, APIStatus.CREATED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Colin").get(0).getId());
    // Construct an API which is visible to employee role only
    apiTags.add("Salary");
    apiTags.add("Bonus");
    uriTemplateMap = getUriTemplateMap(new String[] { "/cash", "/cheque" });
    visibleRoles.add(EMPLOYEE_ROLE);
    addAPIWithGivenData("EmployeeAPI", "5.6.7", "employeeCtx", "Emma", API.Visibility.RESTRICTED, visibleRoles, APIStatus.CREATED.getStatus(), "API for Employees.", apiTags, uriTemplateMap, APIStatus.PUBLISHED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Emma").get(0).getId());
    // Construct an API which is visible to all roles, except admin role
    apiTags.add("Science");
    apiTags.add("Technology");
    uriTemplateMap = getUriTemplateMap(new String[] { "/velocity", "/distance" });
    visibleRoles.add(EMPLOYEE_ROLE);
    visibleRoles.add(MANAGER_ROLE);
    visibleRoles.add(CUSTOMER_ROLE);
    addAPIWithGivenData("NonAdminAPI", "6.7.8", "nonAdmin", "Nancy", API.Visibility.RESTRICTED, visibleRoles, APIStatus.CREATED.getStatus(), "This API should be visible to all roles, except admin role.", apiTags, uriTemplateMap, APIStatus.PROTOTYPED.getStatus());
    visibleRoles.clear();
    apiTags.clear();
    uriTemplateMap.clear();
    apiIDList.add(apiDAO.getAPIs(new HashSet<String>(), "Nancy").get(0).getId());
    return apiIDList;
}
Also used : ArrayList(java.util.ArrayList) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet)

Example 99 with URITemplate

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

the class MappingUtil method toAPIDto.

/**
 * This method converts the API Object from models into APIDTO object.
 *
 * @param api API object
 * @return APIDTO object with provided API object
 */
public static APIDTO toAPIDto(API api) throws IOException {
    APIDTO apidto = new APIDTO();
    apidto.setId(api.getId());
    apidto.setName(api.getName());
    apidto.version(api.getVersion());
    apidto.setContext(api.getContext());
    apidto.setDescription(api.getDescription());
    apidto.setIsDefaultVersion(api.isDefaultVersion());
    apidto.setVisibility(APIDTO.VisibilityEnum.valueOf(api.getVisibility().toString()));
    apidto.setResponseCaching(Boolean.toString(api.isResponseCachingEnabled()));
    apidto.setCacheTimeout(api.getCacheTimeout());
    apidto.setVisibleRoles(new ArrayList<>(api.getVisibleRoles()));
    apidto.setProvider(api.getProvider());
    apidto.setPermission(api.getApiPermission());
    apidto.setLifeCycleStatus(api.getLifeCycleStatus());
    apidto.setWorkflowStatus(api.getWorkflowStatus());
    apidto.setTags(new ArrayList<>(api.getTags()));
    apidto.hasOwnGateway(api.hasOwnGateway());
    apidto.setLabels(new ArrayList<>(api.getLabels()));
    apidto.setTransport(new ArrayList<>(api.getTransport()));
    apidto.setUserPermissionsForApi(api.getUserSpecificApiPermissions());
    apidto.setSecurityScheme(mapSecuritySchemeIntToList(api.getSecurityScheme()));
    for (Policy policy : api.getPolicies()) {
        apidto.addPoliciesItem(policy.getPolicyName());
    }
    apidto.setScopes(api.getScopes());
    BusinessInformation businessInformation = api.getBusinessInformation();
    API_businessInformationDTO apiBusinessInformationDTO = new API_businessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(businessInformation.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(businessInformation.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(businessInformation.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(businessInformation.getTechnicalOwnerEmail());
    apidto.setBusinessInformation(apiBusinessInformationDTO);
    CorsConfiguration corsConfiguration = api.getCorsConfiguration();
    API_corsConfigurationDTO apiCorsConfigurationDTO = new API_corsConfigurationDTO();
    apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAllowCredentials());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAllowMethods());
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAllowOrigins());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isEnabled());
    apidto.setCorsConfiguration(apiCorsConfigurationDTO);
    apidto.setEndpoint(fromEndpointToList(api.getEndpoint()));
    for (UriTemplate uriTemplate : api.getUriTemplates().values()) {
        API_operationsDTO apiOperationsDTO = new API_operationsDTO();
        apiOperationsDTO.setId(uriTemplate.getTemplateId());
        apiOperationsDTO.setUritemplate(uriTemplate.getUriTemplate());
        apiOperationsDTO.setAuthType(uriTemplate.getAuthType());
        apiOperationsDTO.setEndpoint(fromEndpointToList(uriTemplate.getEndpoint()));
        apiOperationsDTO.setHttpVerb(uriTemplate.getHttpVerb());
        apiOperationsDTO.setPolicy(uriTemplate.getPolicy().getPolicyName());
        apiOperationsDTO.setScopes(uriTemplate.getScopes());
        apidto.addOperationsItem(apiOperationsDTO);
    }
    if (api.getApiPolicy() != null) {
        apidto.setApiPolicy(api.getApiPolicy().getPolicyName());
    }
    apidto.setCreatedTime(api.getCreatedTime().toString());
    apidto.setLastUpdatedTime(api.getLastUpdatedTime().toString());
    if (api.getThreatProtectionPolicies() != null) {
        List<String> policyIdList = new ArrayList<>(api.getThreatProtectionPolicies());
        List<API_threatProtectionPolicies_listDTO> listDTOS = new ArrayList<>();
        for (String policyId : policyIdList) {
            API_threatProtectionPolicies_listDTO threatProtectionPoliciesListDTO = new API_threatProtectionPolicies_listDTO();
            threatProtectionPoliciesListDTO.setPolicyId(policyId);
            // set priority when implementing
            // threatProtectionPoliciesListDTO.setPriority(10);
            listDTOS.add(threatProtectionPoliciesListDTO);
        }
        API_threatProtectionPoliciesDTO threatProtectionPoliciesDTO = new API_threatProtectionPoliciesDTO();
        threatProtectionPoliciesDTO.setList(listDTOS);
        apidto.setThreatProtectionPolicies(threatProtectionPoliciesDTO);
    }
    return apidto;
}
Also used : SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) ArrayList(java.util.ArrayList) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) API_threatProtectionPolicies_listDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPolicies_listDTO) API_operationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_operationsDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) API_threatProtectionPoliciesDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPoliciesDTO) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) API_businessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_businessInformationDTO) API_corsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_corsConfigurationDTO)

Example 100 with URITemplate

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

the class ApiImportExportManager method getAPIDetails.

/**
 * Retrieves all API details of the APIs for the given search query. API details consist of:
 *      1. API {@link org.wso2.carbon.apimgt.core.models.API}
 *      2. Document Info {@link org.wso2.carbon.apimgt.core.models.DocumentInfo}
 *      3. Document Content {@link org.wso2.carbon.apimgt.core.models.DocumentContent}
 *      4. Swagger Definition
 *      5. Gateway Definition
 *      6. Thumbnail content
 *
 * @param limit number of max results
 * @param offset starting location when returning a limited set of results
 * @param query searchQuery
 * @return {@link APIDetails} instance
 * @throws APIManagementException if an error occurs while retrieving API details
 */
public Set<APIDetails> getAPIDetails(Integer limit, Integer offset, String query) throws APIManagementException {
    Set<APIDetails> apiDetailSet = new HashSet<>();
    // search for APIs
    List<API> apis = apiPublisher.searchAPIs(limit, offset, query);
    if (apis == null || apis.isEmpty()) {
        // no APIs found, return
        return apiDetailSet;
    }
    // iterate and collect all information
    for (API api : apis) {
        api = apiPublisher.getAPIbyUUID(api.getId());
        // get endpoints at API Level
        Map<String, Endpoint> endpoints = api.getEndpoint();
        if (endpoints.isEmpty()) {
            log.error("No Endpoints found for api: " + api.getName() + ", version: " + api.getVersion());
        // skip this API
        // continue;
        }
        Set<Endpoint> endpointSet = new HashSet<>();
        for (Map.Entry<String, Endpoint> endpointEntry : endpoints.entrySet()) {
            if (APIMgtConstants.GLOBAL_ENDPOINT.equals(endpointEntry.getValue().getApplicableLevel())) {
                Endpoint endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(endpointEntry.getValue().getId())).id("").build();
                endpoints.replace(endpointEntry.getKey(), endpoint);
                endpointSet.add(endpoint);
            }
        }
        // get Endpoints at Resource Level
        Map<String, UriTemplate> uriTemplateMap = api.getUriTemplates();
        uriTemplateMap.forEach((k, v) -> {
            UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
            Map<String, Endpoint> resourceEndpoints = uriTemplateBuilder.getEndpoint();
            resourceEndpoints.forEach((type, value) -> {
                Endpoint endpoint = null;
                if (APIMgtConstants.GLOBAL_ENDPOINT.equals(value.getApplicableLevel())) {
                    try {
                        endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(value.getId())).id("").build();
                        endpointSet.add(endpoint);
                    } catch (APIManagementException e) {
                        log.error("Error in getting endpoints for Resource: " + v.getTemplateId(), e);
                    }
                } else {
                    endpoint = new Endpoint.Builder(value).id("").build();
                }
                resourceEndpoints.replace(type, endpoint);
            });
            uriTemplateMap.replace(k, uriTemplateBuilder.endpoint(resourceEndpoints).build());
        });
        api = new API.APIBuilder(api).endpoint(endpoints).uriTemplates(uriTemplateMap).build();
        // get swagger definition
        String swaggerDefinition;
        try {
            swaggerDefinition = apiPublisher.getApiSwaggerDefinition(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting Swagger configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
            // skip this API
            continue;
        }
        // get gateway configuration
        String gatewayConfig;
        try {
            gatewayConfig = apiPublisher.getApiGatewayConfig(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting gateway configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
            // skip this API
            continue;
        }
        // get doc information
        List<DocumentInfo> documentInfo = null;
        try {
            documentInfo = apiPublisher.getAllDocumentation(api.getId(), 0, Integer.MAX_VALUE);
        } catch (APIManagementException e) {
            log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion(), e);
        // no need to skip the API as docs don't affect API functionality
        }
        Set<DocumentContent> documentContents = new HashSet<>();
        if (documentInfo != null && !documentInfo.isEmpty()) {
            // iterate and collect document content
            for (DocumentInfo aDocumentInfo : documentInfo) {
                try {
                    documentContents.add(apiPublisher.getDocumentationContent(aDocumentInfo.getId()));
                } catch (APIManagementException e) {
                    log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion() + ", doc id: " + aDocumentInfo.getId(), e);
                // no need to skip the API as docs don't affect API functionality
                }
            }
        }
        // get thumbnail
        InputStream thumbnailStream = null;
        try {
            thumbnailStream = apiPublisher.getThumbnailImage(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting thumbnail for api: " + api.getName() + ", version: " + api.getVersion(), e);
        // no need to skip the API as thumbnail don't affect API functionality
        }
        // search operation returns a summary of APIs, need to get all details of APIs
        APIDetails apiDetails = new APIDetails(api, swaggerDefinition);
        apiDetails.setGatewayConfiguration(gatewayConfig);
        apiDetails.setEndpoints(endpointSet);
        if (documentInfo != null && !documentInfo.isEmpty()) {
            apiDetails.addDocumentInformation(documentInfo);
        }
        if (!documentContents.isEmpty()) {
            apiDetails.addDocumentContents(documentContents);
        }
        if (thumbnailStream != null) {
            apiDetails.setThumbnailStream(thumbnailStream);
        }
        apiDetailSet.add(apiDetails);
    }
    return apiDetailSet;
}
Also used : InputStream(java.io.InputStream) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

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