use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testAddApi.
@Test(description = "Test add api with production endpoint")
public void testAddApi() throws APIManagementException, LifecycleException {
/**
* this test method verify the API Add with correct API object get invoked correctly
*/
API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id("").endpoint(SampleTestObjectCreator.getMockEndpointMap());
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
LabelDAO labelDao = Mockito.mock(LabelDAO.class);
GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
APIGateway gateway = Mockito.mock(APIGateway.class);
PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, policyDAO, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
String endpointId = apiBuilder.getEndpoint().get("production").getId();
Endpoint endpoint = new Endpoint.Builder().id(endpointId).name("testEndpoint").build();
Mockito.when(apiDAO.getEndpoint(endpointId)).thenReturn(endpoint);
apiPublisher.addAPI(apiBuilder);
Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
Mockito.verify(apiLifecycleManager, Mockito.times(1)).addLifecycle(APIMgtConstants.API_LIFECYCLE, USER);
// Error path
// When an APIMgtDAOException is being thrown when the API is created
Mockito.doThrow(APIMgtDAOException.class).when(apiDAO).addAPI(apiBuilder.build());
try {
apiPublisher.addAPI(apiBuilder);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "Error occurred while creating the API - " + apiBuilder.getName());
}
// Error path
// When an GatewayException is being thrown when an error occurred while adding API to the Gateway
Mockito.doThrow(GatewayException.class).when(gateway).addAPI(apiBuilder.build());
try {
apiPublisher.addAPI(apiBuilder);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "Error occurred while adding API - " + apiBuilder.getName() + " to gateway");
}
// Error path
// When an APITemplateException is being thrown when generating API configuration for API
Mockito.when(gatewaySourceGenerator.getConfigStringFromTemplate(Mockito.any())).thenThrow(APITemplateException.class);
try {
apiPublisher.addAPI(apiBuilder);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "Error generating API configuration for API " + apiBuilder.getName());
}
}
use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testAddApiSandboxEndpoint.
@Test(description = "Test add api with sandbox endpoint")
public void testAddApiSandboxEndpoint() throws APIManagementException, LifecycleException {
Map<String, Endpoint> endpointMap = new HashMap<>();
Map<String, Endpoint> resourceEndpointMap = new HashMap<>();
Map<String, UriTemplate> uriTemplateMap = new HashMap();
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder();
uriTemplateBuilder.endpoint(resourceEndpointMap);
uriTemplateBuilder.templateId("getApisApiIdGet");
uriTemplateBuilder.uriTemplate("/apis/");
uriTemplateBuilder.authType(APIMgtConstants.AUTH_APPLICATION_LEVEL_TOKEN);
uriTemplateBuilder.policy(APIUtils.getDefaultAPIPolicy());
uriTemplateBuilder.httpVerb("GET");
uriTemplateMap.put("getApisApiIdGet", uriTemplateBuilder.build());
API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id("").endpoint(endpointMap).uriTemplates(uriTemplateMap);
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
String endpointId = String.valueOf(apiBuilder.getEndpoint().get("sandbox"));
Endpoint endpoint = new Endpoint.Builder().id(endpointId).name("testEndpoint").build();
Mockito.when(apiDAO.getEndpoint(endpointId)).thenReturn(endpoint);
GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
APIGateway gateway = Mockito.mock(APIGateway.class);
PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
LabelDAO labelDao = Mockito.mock(LabelDAO.class);
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, policyDAO, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
apiPublisher.addAPI(apiBuilder);
Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
Mockito.verify(apiLifecycleManager, Mockito.times(1)).addLifecycle(APIMgtConstants.API_LIFECYCLE, USER);
}
use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateAPI.
/**
* Updates design and implementation of an existing API. This method must not be used to change API status.
* Implementations should throw an exceptions when such attempts are made. All life cycle state changes
* should be carried out using the changeAPIStatus method of this interface.
*
* @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
* @throws APIManagementException if failed to update API
*/
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
apiBuilder.updatedBy(getUsername());
try {
API originalAPI = getAPIbyUUID(apiBuilder.getId());
if (originalAPI != null) {
// Checks whether the logged in user has the "UPDATE" permission for the API
verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
apiBuilder.createdTime(originalAPI.getCreatedTime());
// workflow status is an internal property and shouldn't be allowed to update externally
apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, true);
validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
createUriTemplateList(apiBuilder, true);
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
API api = apiBuilder.build();
// Add API to gateway
gateway.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
}
if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
if (!checkIfAPIContextExists(api.getContext())) {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> availableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
} else {
throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
}
} else {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
}
if (log.isDebugEnabled()) {
log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
}
} else {
APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
}
} else {
log.error("Couldn't found API with ID " + apiBuilder.getId());
throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
}
} 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 (ParseException e) {
String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
}
use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.
the class APIStoreImplTestCase method testUpdateCompositeApi.
@Test(description = "Update Composite API")
public void testUpdateCompositeApi() throws APIManagementException {
// Add a new Composite API
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);
APIStore apiStore = getApiStoreImpl(idp, null, apiDAO, apiSubscriptionDAO, gatewaySourceGenerator, apiGateway);
String ballerinaImpl = "Ballerina";
apiStore.addCompositeApi(apiBuilder);
CompositeAPI createdAPI = apiBuilder.build();
// Update existing Composite API
apiBuilder = SampleTestObjectCreator.createUniqueCompositeAPI();
apiBuilder.id(createdAPI.getId());
apiBuilder.name(createdAPI.getName());
apiBuilder.provider(createdAPI.getProvider());
apiBuilder.version(createdAPI.getVersion());
apiBuilder.context(createdAPI.getContext());
Mockito.when(apiDAO.getCompositeAPI(apiBuilder.getId())).thenReturn(createdAPI);
Mockito.when(apiDAO.getCompositeAPIGatewayConfig(apiBuilder.getId())).thenReturn(new ByteArrayInputStream(ballerinaImpl.getBytes(StandardCharsets.UTF_8)));
Mockito.when(gatewaySourceGenerator.getGatewayConfigFromSwagger(Matchers.anyString(), Matchers.anyString())).thenReturn(ballerinaImpl);
apiStore.updateCompositeApi(apiBuilder);
CompositeAPI updatedAPI = apiBuilder.build();
Assert.assertEquals(updatedAPI.getId(), createdAPI.getId());
Assert.assertEquals(updatedAPI.getName(), createdAPI.getName());
Assert.assertEquals(updatedAPI.getProvider(), createdAPI.getProvider());
Assert.assertEquals(updatedAPI.getVersion(), createdAPI.getVersion());
Assert.assertEquals(updatedAPI.getContext(), createdAPI.getContext());
}
use of org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testUpdateAPIWithRestrictedVisibility.
@Test(description = "Test UpdateAPI with restricted visibility")
public void testUpdateAPIWithRestrictedVisibility() throws APIManagementException, LifecycleException {
Set<String> visibleRoles = new HashSet<>();
visibleRoles.add(ADMIN_ROLE);
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI().visibility(API.Visibility.RESTRICTED).visibleRoles(visibleRoles);
String uuid = api.getId();
GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
APIGateway gateway = Mockito.mock(APIGateway.class);
IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway, policyDAO);
Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).build());
Mockito.when(apiDAO.isAPIContextExists(api.getContext())).thenReturn(true);
String configString = SampleTestObjectCreator.createSampleGatewayConfig();
Mockito.when(apiDAO.getGatewayConfigOfAPI(uuid)).thenReturn(configString);
Mockito.when(identityProvider.getRoleId(ADMIN_ROLE)).thenReturn(ADMIN_ROLE_ID);
Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
Mockito.when(identityProvider.getRoleId(DEVELOPER_ROLE)).thenReturn(DEVELOPER_ROLE_ID);
apiPublisher.updateAPI(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).id(uuid));
Mockito.verify(apiDAO, Mockito.times(1)).getAPI(uuid);
Mockito.verify(apiDAO, Mockito.times(0)).isAPIContextExists(api.getContext());
Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(uuid, api.lifeCycleStatus(APIStatus.CREATED.getStatus()).build());
}
Aggregations