use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint 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.governance.api.endpoints.dataobjects.Endpoint 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.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class SampleTestObjectCreator method createDefaultAPI.
public static API.APIBuilder createDefaultAPI() {
Set<String> transport = new HashSet<>();
transport.add(HTTP);
transport.add(HTTPS);
Set<String> tags = new HashSet<>();
tags.add(TAG_CLIMATE);
Set<Policy> policies = new HashSet<>();
policies.add(goldSubscriptionPolicy);
policies.add(silverSubscriptionPolicy);
policies.add(bronzeSubscriptionPolicy);
BusinessInformation businessInformation = new BusinessInformation();
businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
Set<String> visibleRoles = new HashSet<>();
visibleRoles.add("testRple");
List<String> labels = new ArrayList<>();
labels.add("testLabel");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setEnabled(true);
corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowOrigins(Arrays.asList("*"));
Map<String, Endpoint> endpointMap = new HashMap<>();
endpointMap.put("TestEndpoint", createMockEndpoint());
API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
Map map = new HashMap();
map.put(DEVELOPER_ROLE_ID, 6);
map.put(ADMIN_ROLE_ID, 15);
apiBuilder.permissionMap(map);
return apiBuilder;
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class APIFileUtilsTestCase method testAPIFileUtils.
@Test
public void testAPIFileUtils() throws Exception {
APIFileUtils.createDirectory(dirPath);
Assert.assertTrue(Files.exists(Paths.get(dirPath)), "Directory doesn't exists");
String filePath = dirPath + File.separatorChar + fileName;
APIFileUtils.createFile(filePath);
Assert.assertTrue(Files.exists(Paths.get(filePath)), "File doesn't exists");
// write content to file
APIFileUtils.writeToFile(dirPath + File.separatorChar + fileName, "This is some test content");
// read content as text
String contentRead = APIFileUtils.readFileContentAsText(dirPath + File.separatorChar + fileName);
Assert.assertEquals(contentRead, "This is some test content");
// read content as stream
InputStream contentReadInputStream = APIFileUtils.readFileContentAsStream(dirPath + File.separatorChar + fileName);
Assert.assertEquals(IOUtils.toString(contentReadInputStream), "This is some test content");
// write stream to filesystem
APIFileUtils.writeStreamToFile(dirPath + File.separatorChar + "write-stream-to-file", contentReadInputStream);
Assert.assertTrue(Files.exists(Paths.get(dirPath + File.separatorChar + "write-stream-to-file")), "File doesn't exists");
// create archive
APIFileUtils.archiveDirectory(new File(dirPath).getAbsolutePath(), new File(parentDir + File.separatorChar).getAbsolutePath(), "my-test-archive");
Assert.assertTrue(Files.exists(Paths.get(parentDir + File.separatorChar + "my-test-archive.zip")), "File doesn't exists");
// find in file system
Assert.assertNotNull(APIFileUtils.findInFileSystem(new File(dirPath), fileName));
// write object as json
GatewayConfigDTO configDTO = new GatewayConfigDTO();
configDTO.setApiName("api1");
configDTO.setConfig("config");
configDTO.setContext("context");
APIFileUtils.writeObjectAsJsonToFile(configDTO, dirPath + File.separatorChar + "object.json");
Assert.assertTrue(Files.exists(Paths.get(dirPath + File.separatorChar + "object.json")), "File doesn't exists");
// write string as json
APIFileUtils.writeStringAsJsonToFile("{\"config\":\"config\"}", dirPath + File.separatorChar + "object-2.json");
Assert.assertTrue(Files.exists(Paths.get(dirPath + File.separatorChar + "object-2.json")), "File doesn't exists");
// list directories
Assert.assertTrue(APIFileUtils.getDirectoryList(parentDir).size() > 0);
// export API Definition
FileApi fileApi = new FileApi();
fileApi.setApiDefinition("api-definition");
fileApi.setName("test-api");
fileApi.setVersion("1.0.0");
fileApi.setProvider("p1");
fileApi.setId("1x1x");
APIFileUtils.exportApiDefinitionToFileSystem(fileApi, parentDir);
Assert.assertTrue(Files.exists(Paths.get(parentDir + File.separatorChar + "api-1x1x.json")), "File doesn't exists");
// export swagger definition
String swaggerDefinition = "{\"swaggerVersion\": \"1.2\",\"apis\": [{\"path\": " + "\"http://localhost:8000/listings/greetings\"," + "\"description\": \"Generating greetings in our application.\"}]}";
APIFileUtils.exportSwaggerDefinitionToFileSystem(swaggerDefinition, new API.APIBuilder("p", "name", "1.0").id("1x1x").build(), parentDir);
Assert.assertTrue(Files.exists(Paths.get(parentDir + File.separatorChar + "swagger-1x1x.json")), "File doesn't exists");
// export endpoint
APIFileUtils.exportEndpointToFileSystem(SampleTestObjectCreator.createMockEndpoint(), parentDir);
Assert.assertTrue(Files.exists(Paths.get(parentDir + File.separatorChar + "Endpoint1.json")), "Endpoint doesn't exists");
// export gatewayconfig
APIFileUtils.exportGatewayConfigToFileSystem("gateway-config-content-goes-here", new API.APIBuilder("p", "name-5", "1.0").id("5x5x").build(), parentDir);
Assert.assertTrue(Files.exists(Paths.get(parentDir + File.separatorChar + "gateway-configuration")), "Gateway config doesn't exists");
// delete file
APIFileUtils.deleteFile(filePath);
Assert.assertFalse(Files.exists(Paths.get(filePath)), "File has not deleted");
// delete directory
APIFileUtils.deleteDirectory(dirPath);
Assert.assertFalse(Files.exists(Paths.get(dirPath)), "Directory has not deleted");
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class EndpointComparatorTestCase method testEndpointComparison.
@Test
public void testEndpointComparison() {
EndPointComparator endPointComparator = new EndPointComparator();
String testUUID = UUID.randomUUID().toString();
Endpoint ep1 = new Endpoint.Builder().endpointConfig("{'type':'http','url':'http://localhost:8280'}").id(testUUID).maxTps(1000L).security("{'enabled':false}").name("Endpoint1").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).type("http").build();
Endpoint ep2 = new Endpoint.Builder().endpointConfig("{'type':'http','url':'http://localhost:8280'}").id(testUUID).maxTps(1000L).security("{'enabled':false}").name("Endpoint1").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).type("http").build();
Endpoint ep3 = new Endpoint.Builder().endpointConfig("{'type':'http','url':'http://localhost:8280'}").id(UUID.randomUUID().toString()).maxTps(2000L).security("{'enabled':true}").name("Endpoint1").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).type("http").build();
Endpoint ep4 = new Endpoint.Builder().endpointConfig("{'type':'http','url':'http://localhost:8280'}").id(UUID.randomUUID().toString()).maxTps(1000L).security("{'enabled':false}").name("Endpoint1").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).type("http").build();
Endpoint ep5 = new Endpoint.Builder().endpointConfig("{'type':'http','url':'http://localhost:6060'}").id(UUID.randomUUID().toString()).maxTps(1000L).security("{'enabled':false}").name("Endpoint1").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).type("http").build();
int endpointComparison1 = endPointComparator.compare(ep1, ep2);
int endpointComparison2 = endPointComparator.compare(ep2, ep3);
int endpointComparison3 = endPointComparator.compare(ep1, ep4);
int endpointComparison4 = endPointComparator.compare(ep1, ep5);
Assert.assertEquals(endpointComparison1, 0, "Endpoints are not equal. ");
Assert.assertNotEquals(endpointComparison2, 0, "Endpoints are equal. ");
Assert.assertEquals(endpointComparison3, 0, "Endpoints are not equal. ");
Assert.assertNotEquals(endpointComparison4, 0, "Endpoints are equal. ");
}
Aggregations