Search in sources :

Example 11 with URITemplate

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

the class MappingUtil method toAPI.

/**
 * This method converts the API model object from the DTO object.
 *
 * @param apidto APIDTO object with API data
 * @return APIBuilder object
 */
public static API.APIBuilder toAPI(APIDTO apidto) throws JsonProcessingException {
    BusinessInformation businessInformation = new BusinessInformation();
    API_businessInformationDTO apiBusinessInformationDTO = apidto.getBusinessInformation();
    if (apiBusinessInformationDTO != null) {
        businessInformation.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
        businessInformation.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
        businessInformation.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
        businessInformation.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
    }
    API_corsConfigurationDTO apiCorsConfigurationDTO = apidto.getCorsConfiguration();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration.setAllowCredentials(apiCorsConfigurationDTO.getAccessControlAllowCredentials());
        corsConfiguration.setAllowHeaders(apiCorsConfigurationDTO.getAccessControlAllowHeaders());
        corsConfiguration.setAllowMethods(apiCorsConfigurationDTO.getAccessControlAllowMethods());
        corsConfiguration.setAllowOrigins(apiCorsConfigurationDTO.getAccessControlAllowOrigins());
        corsConfiguration.setEnabled(apiCorsConfigurationDTO.getCorsConfigurationEnabled());
    }
    List<API_operationsDTO> operationList = apidto.getOperations();
    Map<String, UriTemplate> uriTemplateList = new HashMap<>();
    for (API_operationsDTO operationsDTO : operationList) {
        UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder();
        uriTemplateBuilder.uriTemplate(operationsDTO.getUritemplate());
        uriTemplateBuilder.authType(operationsDTO.getAuthType());
        uriTemplateBuilder.httpVerb(operationsDTO.getHttpVerb());
        uriTemplateBuilder.policy(new APIPolicy(operationsDTO.getPolicy()));
        uriTemplateBuilder.scopes(operationsDTO.getScopes());
        if (operationsDTO.getEndpoint() != null && !operationsDTO.getEndpoint().isEmpty()) {
            uriTemplateBuilder.endpoint(fromEndpointListToMap(operationsDTO.getEndpoint()));
        }
        if (operationsDTO.getId() != null) {
            uriTemplateBuilder.templateId(operationsDTO.getId());
        } else {
            uriTemplateBuilder.templateId(APIUtils.generateOperationIdFromPath(operationsDTO.getUritemplate(), operationsDTO.getHttpVerb()));
        }
        uriTemplateList.put(uriTemplateBuilder.getTemplateId(), uriTemplateBuilder.build());
    }
    Set<Policy> subscriptionPolicies = new HashSet<>();
    apidto.getPolicies().forEach(v -> subscriptionPolicies.add(new SubscriptionPolicy(v)));
    API.APIBuilder apiBuilder = new API.APIBuilder(apidto.getProvider(), apidto.getName(), apidto.getVersion()).id(apidto.getId()).context(apidto.getContext()).description(apidto.getDescription()).lifeCycleStatus(apidto.getLifeCycleStatus()).endpoint(fromEndpointListToMap(apidto.getEndpoint())).visibleRoles(new HashSet<>(apidto.getVisibleRoles())).policies(subscriptionPolicies).apiPermission(apidto.getPermission()).tags(new HashSet<>(apidto.getTags())).labels(new ArrayList<>(apidto.getLabels())).transport(new HashSet<>(apidto.getTransport())).isResponseCachingEnabled(Boolean.valueOf(apidto.getResponseCaching())).businessInformation(businessInformation).uriTemplates(uriTemplateList).corsConfiguration(corsConfiguration).wsdlUri(apidto.getWsdlUri()).scopes(apidto.getScopes()).securityScheme(mapSecuritySchemeListToInt(apidto.getSecurityScheme()));
    if (apidto.getIsDefaultVersion() != null) {
        apiBuilder.isDefaultVersion(apidto.getIsDefaultVersion());
    }
    if (apidto.getVisibility() != null) {
        apiBuilder.visibility(API.Visibility.valueOf(apidto.getVisibility().toString()));
    }
    if (apidto.getCacheTimeout() != null) {
        apiBuilder.cacheTimeout(apidto.getCacheTimeout());
    }
    if (apidto.getApiPolicy() != null) {
        Policy policy = new APIPolicy(apidto.getApiPolicy());
        apiBuilder.apiPolicy(policy);
    }
    if (apidto.getHasOwnGateway() != null) {
        apiBuilder.hasOwnGateway(apidto.getHasOwnGateway());
    }
    if (apidto.getThreatProtectionPolicies() != null) {
        API_threatProtectionPoliciesDTO threatProtectionPoliciesDTO = apidto.getThreatProtectionPolicies();
        List<API_threatProtectionPolicies_listDTO> threatProtectionPolicies_listDTO = threatProtectionPoliciesDTO.getList();
        Set<String> policyIdSet = new HashSet<>();
        for (API_threatProtectionPolicies_listDTO listDTO : threatProtectionPolicies_listDTO) {
            policyIdSet.add(listDTO.getPolicyId());
        }
        apiBuilder.threatProtectionPolicies(policyIdSet);
    }
    return apiBuilder;
}
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) HashMap(java.util.HashMap) 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) API_threatProtectionPoliciesDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPoliciesDTO) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API_businessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_businessInformationDTO) API_corsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_corsConfigurationDTO) HashSet(java.util.HashSet) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) API(org.wso2.carbon.apimgt.core.models.API) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 12 with URITemplate

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

the class ApiImportExportManager method addAPIDetails.

/**
 * Adds the API details
 *
 * @param apiDetails {@link APIDetails} instance
 * @throws APIManagementException if an error occurs while adding API details
 */
public void addAPIDetails(APIDetails apiDetails) throws APIManagementException {
    // update everything
    String swaggerDefinition = apiDetails.getSwaggerDefinition();
    String gatewayConfig = apiDetails.getGatewayConfiguration();
    Map<String, Endpoint> endpointTypeToIdMap = apiDetails.getApi().getEndpoint();
    Map<String, UriTemplate> uriTemplateMap = apiDetails.getApi().getUriTemplates();
    // endpoints
    for (Endpoint endpoint : apiDetails.getEndpoints()) {
        try {
            Endpoint existingEndpoint = apiPublisher.getEndpointByName(endpoint.getName());
            String endpointId;
            if (existingEndpoint == null) {
                // no endpoint by that name, add it
                endpointId = apiPublisher.addEndpoint(endpoint);
            } else {
                endpointId = existingEndpoint.getId();
                if (log.isDebugEnabled()) {
                    log.debug("Endpoint with id " + endpoint.getId() + " already exists, not adding again");
                }
            // endpoint with same name exists, add to endpointTypeToIdMap
            // endpointTypeToIdMap.put(endpoint.getType(), existingEndpoint.getId());
            }
            endpointTypeToIdMap.forEach((String k, Endpoint v) -> {
                if (endpoint.getName().equals(v.getName())) {
                    Endpoint replacedEndpoint = new Endpoint.Builder(v).id(endpointId).build();
                    endpointTypeToIdMap.replace(k, replacedEndpoint);
                }
            });
            uriTemplateMap.forEach(((String templateId, UriTemplate uriTemplate) -> {
                UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(uriTemplate);
                Map<String, Endpoint> uriEndpointMap = uriTemplateBuilder.getEndpoint();
                uriEndpointMap.forEach((String type, Endpoint endpoint1) -> {
                    if (endpoint.getName().equals(endpoint1.getName())) {
                        Endpoint replacedEndpoint = new Endpoint.Builder(endpoint1).id(endpointId).build();
                        uriEndpointMap.replace(type, replacedEndpoint);
                    }
                });
                uriTemplateMap.replace(templateId, uriTemplateBuilder.endpoint(uriEndpointMap).build());
            }));
        } catch (APIManagementException e) {
            // skip adding this API; log and continue
            log.error("Error while adding the endpoint with id: " + endpoint.getId() + ", type: " + endpoint.getType() + " for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
        }
    }
    API.APIBuilder apiBuilder = new API.APIBuilder(apiDetails.getApi());
    apiPublisher.addAPI(apiBuilder.apiDefinition(swaggerDefinition).gatewayConfig(gatewayConfig).endpoint(endpointTypeToIdMap).uriTemplates(uriTemplateMap));
    // docs
    try {
        Set<DocumentInfo> documentInfo = apiDetails.getAllDocumentInformation();
        for (DocumentInfo aDocInfo : documentInfo) {
            apiPublisher.addDocumentationInfo(apiDetails.getApi().getId(), aDocInfo);
        }
        for (DocumentContent aDocContent : apiDetails.getDocumentContents()) {
            // add documentation
            if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.FILE)) {
                apiPublisher.uploadDocumentationFile(aDocContent.getDocumentInfo().getId(), aDocContent.getFileContent(), URLConnection.guessContentTypeFromStream(aDocContent.getFileContent()));
            } else if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
                apiPublisher.addDocumentationContent(aDocContent.getDocumentInfo().getId(), aDocContent.getInlineContent());
            }
        }
    } catch (APIManagementException e) {
        // no need to throw, log and continue
        log.error("Error while adding Document details for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    } catch (IOException e) {
        // no need to throw, log and continue
        log.error("Error while retrieving content type of the File documentation of API : " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    }
    // add thumbnail
    try {
        apiPublisher.saveThumbnailImage(apiDetails.getApi().getId(), apiDetails.getThumbnailStream(), "thumbnail");
    } catch (APIManagementException e) {
        // no need to throw, log and continue
        log.error("Error while adding thumbnail for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    }
}
Also used : IOException(java.io.IOException) 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) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 13 with URITemplate

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

the class MappingUtilTestCase method convertToResourceListDtoTest.

@Test
public void convertToResourceListDtoTest() {
    List<UriTemplate> uriTemplateList = new ArrayList<>();
    uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
    uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
    uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
    uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
    List<UriTemplateDTO> uriTemplateDTOList = MappingUtil.convertToResourceListDto(uriTemplateList);
    Assert.assertEquals(uriTemplateDTOList.size(), uriTemplateList.size());
    for (int i = 0; i < uriTemplateDTOList.size(); i++) {
        Assert.assertEquals(uriTemplateList.get(i).getUriTemplate(), uriTemplateDTOList.get(i).getUriTemplate());
        Assert.assertEquals(uriTemplateList.get(i).getAuthType(), uriTemplateDTOList.get(i).getAuthType());
        Assert.assertEquals(uriTemplateList.get(i).getHttpVerb(), uriTemplateDTOList.get(i).getHttpVerb());
        Assert.assertEquals(uriTemplateList.get(i).getPolicy().getUuid(), uriTemplateDTOList.get(i).getPolicy());
    }
}
Also used : UriTemplateDTO(org.wso2.carbon.apimgt.rest.api.core.dto.UriTemplateDTO) ArrayList(java.util.ArrayList) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) Test(org.testng.annotations.Test)

Example 14 with URITemplate

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

the class APIDefinitionFromSwagger20TestCase method testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity.

@Test
public void testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity() throws IOException {
    APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithoutRootLevelSecurity.yaml"));
    UriTemplate uriTemplate1 = new UriTemplate.UriTemplateBuilder().uriTemplate("/apis").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
    UriTemplate uriTemplate2 = new UriTemplate.UriTemplateBuilder().uriTemplate("/endpoints").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
    Map<String, UriTemplate> hasTemplateMap = new HashMap<>();
    hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate1.getUriTemplate(), uriTemplate1.getHttpVerb()), uriTemplate1);
    hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate2.getUriTemplate(), uriTemplate2.getHttpVerb()), uriTemplate2);
    API api = new API.APIBuilder("admin", "admin", "1.0.0").uriTemplates(hasTemplateMap).id(UUID.randomUUID().toString()).scopes(Arrays.asList("apim:api_create")).build();
    apiDefinitionFromSwagger20.generateMergedResourceDefinition(sampleApi, api);
}
Also used : HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.core.models.API) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Test(org.testng.annotations.Test)

Example 15 with URITemplate

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

the class APIPublisherImplTestCase method testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure.

@Test(description = "Test add api with Api Specific Endpoint", expectedExceptions = { APIManagementException.class })
public void testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure() throws APIManagementException, LifecycleException {
    /**
     * this test method verify the API Add with correct API object get invoked correctly
     */
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    Endpoint globalEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("testEndpoint").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).build();
    Endpoint apiEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("apiEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint resourceEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("resourceEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, globalEndpoint);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, apiEndpoint);
    Map<String, Endpoint> resourceEndpoints = new HashMap();
    resourceEndpoints.put(APIMgtConstants.SANDBOX_ENDPOINT, resourceEndpoint);
    Map<String, UriTemplate> uriTemplateMap = SampleTestObjectCreator.getMockUriTemplates();
    uriTemplateMap.forEach((k, v) -> {
        UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
        uriTemplateBuilder.endpoint(resourceEndpoints);
        uriTemplateMap.replace(k, uriTemplateBuilder.build());
    });
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().endpoint(endpointMap).uriTemplates(uriTemplateMap);
    Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
    APIGateway gateway = Mockito.mock(APIGateway.class);
    LabelDAO labelDao = Mockito.mock(LabelDAO.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, null, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
    Mockito.when(apiDAO.getEndpoint(globalEndpoint.getId())).thenReturn(globalEndpoint);
    Mockito.when(apiDAO.getEndpointByName(apiEndpoint.getName())).thenReturn(null);
    Mockito.when(apiDAO.getEndpointByName(resourceEndpoint.getName())).thenThrow(APIMgtDAOException.class);
    Mockito.when(apiDAO.isAPINameExists(apiBuilder.getName(), USER)).thenReturn(false);
    apiPublisher.addAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(apiEndpoint.getName());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(resourceEndpoint.getName());
}
Also used : HashMap(java.util.HashMap) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) WorkflowExtensionsConfigBuilder(org.wso2.carbon.apimgt.core.workflow.WorkflowExtensionsConfigBuilder) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) LabelDAO(org.wso2.carbon.apimgt.core.dao.LabelDAO) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

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