use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIProviderImplTest method testAddFileToDocumentation.
/**
* This method tests adding file to documentation method.
* @throws Exception
*
* @throws GovernanceException Governance Exception.
*/
@Test
public void testAddFileToDocumentation() throws Exception {
String apiUUID = "xxxxxxxx";
String docUUID = "yyyyyyyy";
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
Tier tier = new Tier("Gold");
Map<String, Tier> tiers = new TreeMap<>();
tiers.put("Gold", tier);
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
final API api = new API(identifier);
api.setStatus(APIConstants.CREATED);
api.setVisibility("public");
api.setAccessControl("all");
api.setTransports("http,https");
api.setContext("/test");
api.setEnvironments(environments);
api.setUriTemplates(uriTemplates);
api.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
apiProvider.addAPI(api);
String fileName = "test.txt";
String contentType = "application/force-download";
Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
doc.setSourceType(DocumentSourceType.FILE);
PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
InputStream inputStream = Mockito.mock(InputStream.class);
// apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
content.setResourceFile(resourceFile);
apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ApiMgtDAO method getURITemplatesOfAPI.
public Set<URITemplate> getURITemplatesOfAPI(String uuid) throws APIManagementException {
String currentApiUuid;
APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
if (apiRevision != null && apiRevision.getApiUUID() != null) {
currentApiUuid = apiRevision.getApiUUID();
} else {
currentApiUuid = uuid;
}
Map<Integer, URITemplate> uriTemplates = new LinkedHashMap<>();
Map<Integer, Set<String>> scopeToURITemplateId = new HashMap<>();
// Check If the API is a Revision
if (apiRevision != null) {
try (Connection conn = APIMgtDBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(SQLConstants.GET_URL_TEMPLATES_OF_API_REVISION_SQL)) {
ps.setString(1, currentApiUuid);
ps.setString(2, uuid);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Integer uriTemplateId = rs.getInt("URL_MAPPING_ID");
String scopeName = rs.getString("SCOPE_NAME");
if (scopeToURITemplateId.containsKey(uriTemplateId) && !StringUtils.isEmpty(scopeName) && !scopeToURITemplateId.get(uriTemplateId).contains(scopeName) && uriTemplates.containsKey(uriTemplateId)) {
Scope scope = new Scope();
scope.setKey(scopeName);
scopeToURITemplateId.get(uriTemplateId).add(scopeName);
uriTemplates.get(uriTemplateId).setScopes(scope);
continue;
}
String urlPattern = rs.getString("URL_PATTERN");
String verb = rs.getString("HTTP_METHOD");
URITemplate uriTemplate = new URITemplate();
uriTemplate.setUriTemplate(urlPattern);
uriTemplate.setHTTPVerb(verb);
uriTemplate.setHttpVerbs(verb);
uriTemplate.setId(uriTemplateId);
String authType = rs.getString("AUTH_SCHEME");
String throttlingTier = rs.getString("THROTTLING_TIER");
if (StringUtils.isNotEmpty(scopeName)) {
Scope scope = new Scope();
scope.setKey(scopeName);
uriTemplate.setScope(scope);
uriTemplate.setScopes(scope);
Set<String> templateScopes = new HashSet<>();
templateScopes.add(scopeName);
scopeToURITemplateId.put(uriTemplateId, templateScopes);
}
uriTemplate.setAuthType(authType);
uriTemplate.setAuthTypes(authType);
uriTemplate.setThrottlingTier(throttlingTier);
uriTemplate.setThrottlingTiers(throttlingTier);
uriTemplate.setId(uriTemplateId);
InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
if (mediationScriptBlob != null) {
String script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
uriTemplate.setMediationScript(script);
uriTemplate.setMediationScripts(verb, script);
}
uriTemplates.put(uriTemplateId, uriTemplate);
}
}
setAssociatedAPIProducts(currentApiUuid, uriTemplates);
setOperationPolicies(apiRevision.getRevisionUUID(), uriTemplates);
} catch (SQLException e) {
handleException("Failed to get URI Templates of API with UUID " + uuid, e);
}
} else {
try (Connection conn = APIMgtDBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(SQLConstants.GET_URL_TEMPLATES_OF_API_SQL)) {
ps.setString(1, currentApiUuid);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Integer uriTemplateId = rs.getInt("URL_MAPPING_ID");
String scopeName = rs.getString("SCOPE_NAME");
if (scopeToURITemplateId.containsKey(uriTemplateId) && !StringUtils.isEmpty(scopeName) && !scopeToURITemplateId.get(uriTemplateId).contains(scopeName) && uriTemplates.containsKey(uriTemplateId)) {
Scope scope = new Scope();
scope.setKey(scopeName);
scopeToURITemplateId.get(uriTemplateId).add(scopeName);
uriTemplates.get(uriTemplateId).setScopes(scope);
continue;
}
String urlPattern = rs.getString("URL_PATTERN");
String verb = rs.getString("HTTP_METHOD");
URITemplate uriTemplate = new URITemplate();
uriTemplate.setUriTemplate(urlPattern);
uriTemplate.setHTTPVerb(verb);
uriTemplate.setHttpVerbs(verb);
String authType = rs.getString("AUTH_SCHEME");
String throttlingTier = rs.getString("THROTTLING_TIER");
if (StringUtils.isNotEmpty(scopeName)) {
Scope scope = new Scope();
scope.setKey(scopeName);
uriTemplate.setScope(scope);
uriTemplate.setScopes(scope);
Set<String> templateScopes = new HashSet<>();
templateScopes.add(scopeName);
scopeToURITemplateId.put(uriTemplateId, templateScopes);
}
uriTemplate.setAuthType(authType);
uriTemplate.setAuthTypes(authType);
uriTemplate.setThrottlingTier(throttlingTier);
uriTemplate.setThrottlingTiers(throttlingTier);
uriTemplate.setId(uriTemplateId);
InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
if (mediationScriptBlob != null) {
String script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
uriTemplate.setMediationScript(script);
uriTemplate.setMediationScripts(verb, script);
}
uriTemplates.put(uriTemplateId, uriTemplate);
}
}
setAssociatedAPIProducts(currentApiUuid, uriTemplates);
setOperationPolicies(currentApiUuid, uriTemplates);
} catch (SQLException e) {
handleException("Failed to get URI Templates of API with UUID " + currentApiUuid, e);
}
}
return new LinkedHashSet<>(uriTemplates.values());
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ApiMgtDAO method setAssociatedAPIProductsURLMappings.
private void setAssociatedAPIProductsURLMappings(String uuid, Map<Integer, URITemplate> uriTemplates) throws SQLException {
try (Connection conn = APIMgtDBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(SQLConstants.GET_ASSOCIATED_API_PRODUCT_URL_TEMPLATES_SQL)) {
ps.setString(1, uuid);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String productName = rs.getString("API_NAME");
String productVersion = rs.getString("API_VERSION");
String productProvider = rs.getString("API_PROVIDER");
int uriTemplateId = rs.getInt("URL_MAPPING_ID");
URITemplate uriTemplate = uriTemplates.get(uriTemplateId);
if (uriTemplate != null) {
APIProductIdentifier productIdentifier = new APIProductIdentifier(productProvider, productName, productVersion);
uriTemplate.addUsedByProduct(productIdentifier);
}
}
}
}
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIProviderImplTest method testSearchAPIs.
@Test
public void testSearchAPIs() throws APIManagementException, RegistryException {
// APIs of the provider
API api1 = new API(new APIIdentifier("admin", "API1", "1.0.1"));
api1.setContext("api1context");
api1.setStatus(APIConstants.PUBLISHED);
api1.setDescription("API 1 Desciption");
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
api1.setUriTemplates(uriTemplates);
API api2 = new API(new APIIdentifier("admin", "API2", "1.0.0"));
api2.setContext("api2context");
api2.setStatus(APIConstants.CREATED);
api2.setDescription("API 2 Desciption");
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
prepareForGetAPIsByProvider(artifactManager, apiProvider, "admin", api1, api2);
// Search by Name matching both APIs
List<API> foundApiList0 = apiProvider.searchAPIs("API", "Name", "admin");
Assert.assertNotNull(foundApiList0);
Assert.assertEquals(2, foundApiList0.size());
// Search by exact name
List<API> foundApiList1 = apiProvider.searchAPIs("API1", "Name", "admin");
Assert.assertNotNull(foundApiList1);
Assert.assertEquals(1, foundApiList1.size());
// Search by exact provider
List<API> foundApiList2 = apiProvider.searchAPIs("admin", "Provider", "admin");
Assert.assertNotNull(foundApiList2);
Assert.assertEquals(2, foundApiList2.size());
// Search by exact version
List<API> foundApiList3 = apiProvider.searchAPIs("1.0.0", "Version", "admin");
Assert.assertNotNull(foundApiList3);
Assert.assertEquals(1, foundApiList3.size());
// Search by exact context
List<API> foundApiList4 = apiProvider.searchAPIs("api1context", "Context", "admin");
Assert.assertNotNull(foundApiList4);
Assert.assertEquals(1, foundApiList4.size());
// Search by exact context
List<API> foundApiList5 = apiProvider.searchAPIs("api2context", "Context", "admin");
Assert.assertNotNull(foundApiList5);
Assert.assertEquals(1, foundApiList5.size());
// Search by wrong context
List<API> foundApiList6 = apiProvider.searchAPIs("test", "Context", "admin");
Assert.assertNotNull(foundApiList6);
Assert.assertEquals(0, foundApiList6.size());
// Search by status
List<API> foundApiList7 = apiProvider.searchAPIs("Published", "Status", "admin");
Assert.assertNotNull(foundApiList7);
Assert.assertEquals(1, foundApiList7.size());
// Search by Description
List<API> foundApiList8 = apiProvider.searchAPIs("API 1 Desciption", "Description", "admin");
Assert.assertNotNull(foundApiList8);
Assert.assertEquals(1, foundApiList8.size());
// Search by Description
List<API> foundApiList9 = apiProvider.searchAPIs("API", "Description", "admin");
Assert.assertNotNull(foundApiList9);
Assert.assertEquals(2, foundApiList9.size());
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIProviderImplTest method testUpdateAPI_InCreatedState.
@Test
public void testUpdateAPI_InCreatedState() throws Exception {
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
Set<URITemplate> newUriTemplates = new HashSet<URITemplate>();
Tier tier = new Tier("Gold");
Map<String, Tier> tiers = new TreeMap<>();
tiers.put("Gold", tier);
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
URITemplate uriTemplate2 = new URITemplate();
uriTemplate2.setHTTPVerb("PUT");
uriTemplate2.setAuthType("Application");
uriTemplate2.setUriTemplate("/update");
uriTemplate2.setThrottlingTier("Gold");
newUriTemplates.add(uriTemplate1);
newUriTemplates.add(uriTemplate2);
final API api = new API(identifier);
api.setStatus(APIConstants.CREATED);
api.setVisibility("public");
api.setAccessControl("all");
api.setTransports("http,https");
api.setContext("/test");
api.setEnvironments(environments);
api.setUriTemplates(newUriTemplates);
api.setOrganization("carbon.super");
API oldApi = new API(identifier);
oldApi.setStatus(APIConstants.CREATED);
oldApi.setVisibility("public");
oldApi.setAccessControl("all");
oldApi.setContext("/test");
oldApi.setEnvironments(environments);
api.setUriTemplates(uriTemplates);
oldApi.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
Documentation documentation = documentationList.get(1);
Mockito.when(APIUtil.getAPIDocPath(api.getId())).thenReturn(documentation.getFilePath());
APIProviderImplWrapper apiProviderImplWrapper = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO);
Resource docResource = Mockito.mock(Resource.class);
Mockito.when(docResource.getUUID()).thenReturn(documentation.getId());
Mockito.when(apiProviderImplWrapper.registry.get(documentation.getFilePath())).thenReturn(docResource);
GenericArtifact docArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(documentation.getId())).thenReturn(docArtifact);
Mockito.when(APIUtil.getDocumentation(docArtifact)).thenReturn(documentation);
Mockito.when(docArtifact.getPath()).thenReturn(artifactPath);
PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
String[] roles = { "admin", "subscriber" };
APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
Mockito.when(docArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("docFilePath");
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, oldApi)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
apiProvider.addAPI(oldApi);
// mock has permission
Resource apiSourceArtifact = Mockito.mock(Resource.class);
Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
String apiSourcePath = "path";
PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
PowerMockito.when(APIUtil.getAPIPath(oldApi.getId())).thenReturn(apiSourcePath);
PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
// API Status is CREATED and user has permission
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_PUBLISH)).thenReturn(true);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_CREATE)).thenReturn(true);
Mockito.when(apimgtDAO.getDefaultVersion(identifier)).thenReturn("1.0.0");
Mockito.when(apimgtDAO.getPublishedDefaultVersion(identifier)).thenReturn("1.0.0");
// updateDefaultAPIInRegistry
String defaultAPIPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
Resource defaultAPISourceArtifact = Mockito.mock(Resource.class);
String defaultAPIUUID = "12640983600";
Mockito.when(defaultAPISourceArtifact.getUUID()).thenReturn(defaultAPIUUID);
Mockito.when(apiProvider.registry.get(defaultAPIPath)).thenReturn(defaultAPISourceArtifact);
GenericArtifact defaultAPIArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(defaultAPIUUID)).thenReturn(defaultAPIArtifact);
Mockito.doNothing().when(artifactManager).updateGenericArtifact(defaultAPIArtifact);
TestUtils.mockAPIMConfiguration(APIConstants.API_GATEWAY_TYPE, APIConstants.API_GATEWAY_TYPE_SYNAPSE, -1234);
// updateApiArtifact
PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
Mockito.when(artifact.getId()).thenReturn("12640983654");
PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
// Mock Updating API
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
apiProvider.createAPI(api);
return null;
}
}).when(artifactManager).updateGenericArtifact(artifact);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
PowerMockito.when(apiPersistenceInstance.getPublisherAPI(any(Organization.class), any(String.class))).thenReturn(publisherAPI);
Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
apiProvider.updateAPI(api, oldApi);
Assert.assertEquals(0, api.getEnvironments().size());
tiers.remove("Gold", tier);
tier = new Tier("Unlimited");
tiers.put("Unlimited", tier);
try {
apiProvider.updateAPI(api, oldApi);
} catch (APIManagementException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid x-throttling tier Gold found in api definition for " + "resource POST /add"));
}
}
Aggregations