Search in sources :

Example 66 with GatewaySourceGenerator

use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testSaveSwagger20DefinitionException.

@Test(description = "Exception when saving swagger definition for API", expectedExceptions = APIManagementException.class)
public void testSaveSwagger20DefinitionException() throws APIManagementException, IOException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    API api = SampleTestObjectCreator.createDefaultAPI().build();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api);
    Mockito.doThrow(new APIMgtDAOException("Couldn't update the Swagger Definition")).when(apiDAO).updateApiDefinition(uuid, SampleTestObjectCreator.apiDefinition, USER);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, gatewaySourceGenerator, gateway, keyManager);
    Mockito.when(identityProvider.getRoleName(SampleTestObjectCreator.DEVELOPER_ROLE_ID)).thenReturn(DEVELOPER_ROLE);
    Mockito.when(keyManager.retrieveScope("apim:api_create")).thenReturn(new Scope("apim:api_create", "Create " + "API"));
    String oldSwagger = IOUtils.toString(new FileInputStream("src" + File.separator + "test" + File.separator + "resources" + File.separator + "swagger" + File.separator + "swaggerWithAuthorization" + ".yaml"));
    Mockito.when(identityProvider.getRoleName(SampleTestObjectCreator.ADMIN_ROLE_ID)).thenReturn(ADMIN_ROLE);
    Mockito.when(apiDAO.getApiSwaggerDefinition(uuid)).thenReturn(oldSwagger);
    apiPublisher.saveSwagger20Definition(uuid, SampleTestObjectCreator.apiDefinition);
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Scope(org.wso2.carbon.apimgt.core.models.Scope) API(org.wso2.carbon.apimgt.core.models.API) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) FileInputStream(java.io.FileInputStream) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Test(org.testng.annotations.Test)

Example 67 with GatewaySourceGenerator

use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.

the class APIPublisherImpl method saveSwagger20Definition.

/**
 * {@inheritDoc}
 */
@Override
public void saveSwagger20Definition(String apiId, String jsonText) throws APIManagementException {
    try {
        LocalDateTime localDateTime = LocalDateTime.now();
        Map<String, String> oldScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(apiId));
        Map<String, String> newScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(jsonText);
        Map<String, String> updatedScopes = new HashMap<>(newScopes);
        updatedScopes.keySet().retainAll(oldScopes.keySet());
        oldScopes.keySet().removeAll(updatedScopes.keySet());
        newScopes.keySet().removeAll(updatedScopes.keySet());
        for (Map.Entry<String, String> scopeEntry : newScopes.entrySet()) {
            getKeyManager().registerScope(new Scope(scopeEntry.getKey(), scopeEntry.getValue()));
        }
        for (Map.Entry<String, String> scopeEntry : oldScopes.entrySet()) {
            getKeyManager().deleteScope(scopeEntry.getKey());
        }
        for (Map.Entry<String, String> scopeEntry : updatedScopes.entrySet()) {
            Scope scope = getKeyManager().retrieveScope(scopeEntry.getKey());
            scope.setDescription(scopeEntry.getValue());
            getKeyManager().updateScope(scope);
        }
        API api = getAPIbyUUID(apiId);
        Map<String, UriTemplate> oldUriTemplateMap = api.getUriTemplates();
        List<APIResource> apiResourceList = apiDefinitionFromSwagger20.parseSwaggerAPIResources(new StringBuilder(jsonText));
        Map<String, UriTemplate> updatedUriTemplateMap = new HashMap<>();
        for (APIResource apiResource : apiResourceList) {
            updatedUriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
        }
        Map<String, UriTemplate> uriTemplateMapNeedTobeUpdate = APIUtils.getMergedUriTemplates(oldUriTemplateMap, updatedUriTemplateMap);
        API.APIBuilder apiBuilder = new API.APIBuilder(api);
        apiBuilder.uriTemplates(uriTemplateMapNeedTobeUpdate);
        createUriTemplateList(apiBuilder, true);
        apiBuilder.updatedBy(getUsername());
        apiBuilder.lastUpdatedTime(localDateTime);
        api = apiBuilder.build();
        GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
        APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
        gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
        String existingGatewayConfig = getApiGatewayConfig(apiId);
        String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(existingGatewayConfig, jsonText);
        getApiDAO().updateAPI(apiId, api);
        getApiDAO().updateApiDefinition(apiId, jsonText, getUsername());
        getApiDAO().updateGatewayConfig(apiId, updatedGatewayConfig, getUsername());
    } catch (APIMgtDAOException e) {
        String errorMsg = "Couldn't update the Swagger Definition";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Scope(org.wso2.carbon.apimgt.core.models.Scope) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) Map(java.util.Map) HashMap(java.util.HashMap) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 68 with GatewaySourceGenerator

use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.

the class APIStoreImpl method updateCompositeApi.

/**
 * {@inheritDoc}
 */
@Override
public void updateCompositeApi(CompositeAPI.Builder apiBuilder) throws APIManagementException {
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    CompositeAPI originalAPI = getApiDAO().getCompositeAPI(apiBuilder.getId());
    apiBuilder.createdTime(originalAPI.getCreatedTime());
    // workflow status is an internal property and shouldn't be allowed to update externally
    apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
    APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
    try {
        String updatedSwagger = apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder);
        InputStream gatewayConfig = getApiDAO().getCompositeAPIGatewayConfig(apiBuilder.getId());
        GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
        APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
        gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
        String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(IOUtils.toString(gatewayConfig, StandardCharsets.UTF_8), updatedSwagger);
        CompositeAPI api = apiBuilder.build();
        if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
            if (isContextExist(api.getContext())) {
                throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
            }
        }
        // publishing config to gateway
        gateway.addCompositeAPI(api);
        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
        getApiDAO().updateCompositeAPIGatewayConfig(api.getId(), new ByteArrayInputStream(updatedGatewayConfig.getBytes(StandardCharsets.UTF_8)), api.getUpdatedBy());
        if (log.isDebugEnabled()) {
            log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (IOException e) {
        String errorMsg = "Error occurred while reading gateway configuration the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_DAO_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) IOException(java.io.IOException) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 69 with GatewaySourceGenerator

use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.

the class APIStoreImpl method setGatewayDefinitionSource.

private void setGatewayDefinitionSource(CompositeAPI.Builder apiBuilder) throws APIManagementException {
    List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
    List<TemplateBuilderDTO> resourceList = new ArrayList<>();
    String appId = null;
    List<CompositeAPIEndpointDTO> endpointDTOs = new ArrayList<CompositeAPIEndpointDTO>();
    try {
        appId = apiBuilder.getApplicationId();
        List<Subscription> subscriptions = getApiSubscriptionDAO().getAPISubscriptionsByApplication(apiBuilder.getApplicationId(), ApiType.STANDARD);
        for (Subscription subscription : subscriptions) {
            CompositeAPIEndpointDTO endpointDTO = new CompositeAPIEndpointDTO();
            API api = subscription.getApi();
            endpointDTO.setEndpointName(api.getName());
            // TODO: currently only HTTPS endpoint considered. Websocket APIs and http transport should considered
            endpointDTO.setTransportType(APIMgtConstants.HTTPS);
            // TODO: replace host with gateway domain host
            String endpointUrl = APIMgtConstants.HTTPS + APIMgtConstants.WEB_PROTOCOL_SUFFIX + config.getHostname() + "/" + api.getContext() + "/" + api.getVersion();
            endpointDTO.setEndpointUrl(endpointUrl);
            endpointDTOs.add(endpointDTO);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error while getting subscriptions of the application " + appId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    for (UriTemplate uriTemplate : list) {
        TemplateBuilderDTO dto = new TemplateBuilderDTO();
        dto.setTemplateId(uriTemplate.getTemplateId());
        dto.setUriTemplate(uriTemplate.getUriTemplate());
        dto.setHttpVerb(uriTemplate.getHttpVerb());
        resourceList.add(dto);
    }
    GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
    APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
    gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
    String gatewayConfig = gatewaySourceGenerator.getCompositeAPIConfigStringFromTemplate(resourceList, endpointDTOs);
    if (log.isDebugEnabled()) {
        log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
    }
    apiBuilder.gatewayConfig(gatewayConfig);
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) ArrayList(java.util.ArrayList) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) CompositeAPIEndpointDTO(org.wso2.carbon.apimgt.core.template.dto.CompositeAPIEndpointDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) TemplateBuilderDTO(org.wso2.carbon.apimgt.core.template.dto.TemplateBuilderDTO) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) Subscription(org.wso2.carbon.apimgt.core.models.Subscription) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 70 with GatewaySourceGenerator

use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.

the class APIStoreImplTestCase method testAddCompositeApi.

@Test(description = "Add Composite API")
public void testAddCompositeApi() throws APIManagementException {
    CompositeAPI.Builder apiBuilder = SampleTestObjectCreator.createUniqueCompositeAPI();
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APISubscriptionDAO apiSubscriptionDAO = Mockito.mock(APISubscriptionDAO.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway apiGateway = Mockito.mock(APIGateway.class);
    IdentityProvider idp = Mockito.mock(IdentityProvider.class);
    KeyManager km = Mockito.mock(KeyManager.class);
    APIStore apiStore = getApiStoreImpl(idp, km, apiDAO, apiSubscriptionDAO, gatewaySourceGenerator, apiGateway);
    apiStore.addCompositeApi(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).addApplicationAssociatedAPI(apiBuilder.build());
}
Also used : APISubscriptionDAO(org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)71 Test (org.testng.annotations.Test)65 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)65 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)59 API (org.wso2.carbon.apimgt.core.models.API)59 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)34 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)34 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)34 LabelDAO (org.wso2.carbon.apimgt.core.dao.LabelDAO)28 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)28 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)24 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)22 HashMap (java.util.HashMap)20 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)20 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)17 LifecycleState (org.wso2.carbon.lcm.core.impl.LifecycleState)16 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)13 FileInputStream (java.io.FileInputStream)12 Scope (org.wso2.carbon.apimgt.core.models.Scope)12 WorkflowExtensionsConfigBuilder (org.wso2.carbon.apimgt.core.workflow.WorkflowExtensionsConfigBuilder)11