use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetDocumentationContent.
@Test
public void testGetDocumentationContent() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException {
int tenantId = -1234;
UserRegistry registry = Mockito.mock(UserRegistry.class);
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapperExtended(genericArtifactManager, registryService, registry, tenantManager);
Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenThrow(UserStoreException.class).thenReturn(tenantId);
APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
String docName = "doc1";
try {
abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.fail("User store exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Failed to get document content found for documentation:"));
}
Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenThrow(RegistryException.class).thenReturn(registry);
try {
abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.fail("Registry exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("No document content found for documentation:"));
}
Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(false, true, true);
String docContent = abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.assertNull(docContent);
String docObject = "samlple doc content";
Resource resource = new ResourceImpl();
resource.setContent(docObject.getBytes(StandardCharsets.UTF_8));
Mockito.when(registry.get(Mockito.anyString())).thenReturn(resource);
docContent = abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.assertEquals(docContent, docObject);
abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, registryService, registry, tenantManager);
docContent = abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.assertEquals(docContent, docObject);
Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).thenReturn(registry);
abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN_1;
docContent = abstractAPIManager.getDocumentationContent(identifier, docName);
Assert.assertEquals(docContent, docObject);
}
use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetAllDocumentationWithLoggedUser.
@Test
public void testGetAllDocumentationWithLoggedUser() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException {
int tenantId = -1234;
UserRegistry registry = Mockito.mock(UserRegistry.class);
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, registryService, registry, tenantManager);
Mockito.when(tenantManager.getTenantId(SAMPLE_TENANT_DOMAIN)).thenThrow(UserStoreException.class).thenReturn(tenantId);
APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
String loggedInUser = "admin";
abstractAPIManager.registry = registry;
GenericArtifact genericArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION, "sample");
genericArtifact.setAttribute(APIConstants.DOC_TYPE, "Other");
genericArtifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, "URL");
String apiDocPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR + RegistryConstants.PATH_SEPARATOR;
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.when(APIUtil.getAPIOrAPIProductDocPath(identifier)).thenReturn(apiDocPath);
Resource resource1 = new ResourceImpl();
resource1.setUUID(SAMPLE_RESOURCE_ID);
Mockito.when(genericArtifact.getPath()).thenReturn("test");
String docName = "sample";
Documentation documentation = new Documentation(DocumentationType.HOWTO, docName);
PowerMockito.when(APIUtil.getDocumentation(genericArtifact)).thenReturn(documentation);
Mockito.when(registry.resourceExists(apiDocPath)).thenReturn(true);
try {
abstractAPIManager.getAllDocumentation(identifier, loggedInUser);
Assert.fail("Registry exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Failed to get documentations for api"));
}
Resource resource2 = new ResourceImpl();
resource2.setUUID(SAMPLE_RESOURCE_ID);
Mockito.when(genericArtifactManager.getGenericArtifact(SAMPLE_RESOURCE_ID)).thenReturn(genericArtifact);
String documentationName = "doc1";
Collection documentCollection = new CollectionImpl();
documentCollection.setChildren(new String[] { apiDocPath + documentationName, apiDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR });
Mockito.when(registry.get(apiDocPath)).thenReturn(documentCollection);
Mockito.when(registry.get(apiDocPath + documentationName)).thenReturn(resource2);
PowerMockito.when(APIUtil.getDocumentation(genericArtifact, loggedInUser)).thenReturn(documentation);
List<Documentation> documentationList = abstractAPIManager.getAllDocumentation(identifier, loggedInUser);
Assert.assertNotNull(documentationList);
Assert.assertEquals(documentationList.size(), 1);
String contentPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR + RegistryConstants.PATH_SEPARATOR + RegistryConstants.PATH_SEPARATOR + documentationName;
genericArtifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, "In line");
genericArtifact.setAttribute(APIConstants.DOC_NAME, documentationName);
ResourceDO resourceDO = new ResourceDO();
resourceDO.setLastUpdatedOn(12344567);
Resource resource3 = new ResourceImpl(contentPath, resourceDO);
Mockito.when(registry.get(contentPath)).thenReturn(resource3);
documentationList = abstractAPIManager.getAllDocumentation(identifier, loggedInUser);
Assert.assertNotNull(documentationList);
Assert.assertEquals(documentationList.size(), 1);
}
use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPI.
/**
* Updates an existing API
*
* @param api API
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update API
* @throws org.wso2.carbon.apimgt.api.FaultGatewaysException on Gateway Failure
*/
@Override
public void updateAPI(API api) throws APIManagementException, FaultGatewaysException {
boolean isValid = isAPIUpdateValid(api);
if (!isValid) {
throw new APIManagementException(" User doesn't have permission for update");
}
API oldApi = getAPIbyUUID(api.getUuid(), api.getOrganization());
String organization = api.getOrganization();
if (!oldApi.getStatus().equals(api.getStatus())) {
// Use changeAPIStatus for that kind of updates.
throw new APIManagementException("Invalid API update operation involving API status changes");
}
validateKeyManagers(api);
Gson gson = new Gson();
Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
Map<String, String> newMonetizationProperties = gson.fromJson(api.getMonetizationProperties().toString(), HashMap.class);
if (newMonetizationProperties != null) {
for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
String newValue = newMonetizationProperties.get(entry.getKey());
if (StringUtils.isAllBlank(newValue)) {
newMonetizationProperties.put(entry.getKey(), entry.getValue());
}
}
JSONParser parser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
api.setMonetizationProperties(jsonObj);
} catch (ParseException e) {
throw new APIManagementException("Error when parsing monetization properties ", e);
}
}
}
String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());
// Update WSDL in the registry
if (api.getWsdlUrl() != null && api.getWsdlResource() == null) {
updateWsdlFromUrl(api);
}
if (api.getWsdlResource() != null) {
updateWsdlFromResourceFile(api);
}
boolean updatePermissions = false;
if (APIUtil.isAccessControlEnabled()) {
if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
} else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
updateEndpointSecurity(oldApi, api);
String apiUUid = updateApiArtifact(api, true, updatePermissions);
api.setUuid(apiUUid);
if (!oldApi.getContext().equals(api.getContext())) {
api.setApiHeaderChanged(true);
}
int tenantId;
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
try {
tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new APIManagementException("Error in retrieving Tenant Information while updating api :" + api.getId().getApiName(), e);
}
validateResourceThrottlingTiers(api, tenantDomain);
// get product resource mappings on API before updating the API. Update uri templates on api will remove all
// product mappings as well.
List<APIProductResource> productResources = apiMgtDAO.getProductMappingsForAPI(api);
updateAPI(api, tenantId, userNameWithoutChange);
updateProductResourceMappings(api, organization, productResources);
if (log.isDebugEnabled()) {
log.debug("Successfully updated the API: " + api.getId() + " in the database");
}
JSONObject apiLogObject = new JSONObject();
apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
// update doc visibility
List<Documentation> docsList = getAllDocumentation(api.getId());
if (docsList != null) {
Iterator it = docsList.iterator();
while (it.hasNext()) {
Object docsObject = it.next();
Documentation docs = (Documentation) docsObject;
updateDocVisibility(api, docs);
}
}
// notify key manager with API update
registerOrUpdateResourceInKeyManager(api, tenantDomain);
int apiId = apiMgtDAO.getAPIID(api.getUuid());
if (publishedDefaultVersion != null) {
if (api.isPublishedDefaultVersion() && !api.getId().getVersion().equals(publishedDefaultVersion)) {
APIIdentifier previousDefaultVersionIdentifier = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), publishedDefaultVersion);
sendUpdateEventToPreviousDefaultVersion(previousDefaultVersionIdentifier, organization);
}
}
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
// Extracting API details for the recommendation system
if (recommendationEnvironment != null) {
RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.ADD_API);
Thread recommendationThread = new Thread(extractor);
recommendationThread.start();
}
}
use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.
the class APIProviderImpl method copyAllDocumentation.
/**
* Copies current Documentation into another version of the same API.
*
* @param toVersion Version to which Documentation should be copied.
* @param apiId id of the APIIdentifier
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to copy docs
*/
public void copyAllDocumentation(APIIdentifier apiId, String toVersion) throws APIManagementException {
String oldVersion = APIUtil.getAPIDocPath(apiId);
String newVersion = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + toVersion + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR;
try {
Resource resource = registry.get(oldVersion);
if (resource instanceof org.wso2.carbon.registry.core.Collection) {
String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
for (String docPath : docsPaths) {
registry.copy(docPath, newVersion);
}
}
} catch (RegistryException e) {
handleException("Failed to copy docs to new version : " + newVersion, e);
}
}
use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.
the class APIProviderImpl method updateDocumentPermissions.
private void updateDocumentPermissions(API api, API oldApi) throws APIManagementException {
boolean updatePermissions = false;
if (APIUtil.isAccessControlEnabled()) {
if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
} else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
updatePermissions = true;
}
String visibleRolesList = api.getVisibleRoles();
String[] visibleRoles = new String[0];
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
// TODO check if registry.beginTransaction(); flow is needed
List<Documentation> docs = getAllDocumentation(api.getId());
if (updatePermissions) {
APIManagerConfiguration config = getAPIManagerConfiguration();
boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
String docRootPath = APIUtil.getAPIDocPath(api.getId());
if (isSetDocLevelPermissions) {
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
} else {
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
}
} else {
if (docs != null) {
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
}
}
}
}
// update doc visibility
if (docs != null) {
Iterator it = docs.iterator();
while (it.hasNext()) {
Object docsObject = it.next();
Documentation doc = (Documentation) docsObject;
updateDocVisibility(api, doc);
}
}
}
Aggregations