use of org.wso2.carbon.apimgt.api.model.Wsdl in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetWsdl.
@Test
public void testGetWsdl() throws APIManagementException, RegistryException, IOException {
Resource resourceMock = Mockito.mock(Resource.class);
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
String wsdlName = identifier.getProviderName() + "--" + identifier.getApiName() + identifier.getVersion() + ".wsdl";
String wsdlResourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + wsdlName;
Resource resource = new ResourceImpl(wsdlResourcePath, new ResourceDO());
Mockito.when(registry.get(wsdlResourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
Mockito.when(registry.resourceExists(wsdlResourcePath)).thenReturn(true);
try {
abstractAPIManager.getWSDL(identifier);
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Error while getting wsdl file from the registry"));
}
String wsdlContent = "sample wsdl";
resource.setContent(wsdlContent);
InputStream inputStream = new ArrayInputStream();
Mockito.when(resourceMock.getContentStream()).thenReturn(inputStream);
Assert.assertEquals(wsdlContent, IOUtils.toString(abstractAPIManager.getWSDL(identifier).getContent()));
PowerMockito.mockStatic(IOUtils.class);
}
use of org.wso2.carbon.apimgt.api.model.Wsdl in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetAllWsdls.
@Test
public void testGetAllWsdls() throws RegistryException, APIManagementException {
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
Collection parentCollection = new CollectionImpl();
String wsdlResourcepath = APIConstants.API_WSDL_RESOURCE;
String resourcePath = wsdlResourcepath + "/wsdl1";
parentCollection.setChildren(new String[] { resourcePath });
Mockito.when(registry.get(wsdlResourcepath)).thenReturn(parentCollection);
Resource resource = new ResourceImpl();
Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
Mockito.when(registry.resourceExists(wsdlResourcepath)).thenReturn(true);
try {
abstractAPIManager.getAllWsdls();
Assert.fail("Exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Failed to get wsdl list"));
}
resource.setUUID(SAMPLE_RESOURCE_ID);
List<Wsdl> wsdls = abstractAPIManager.getAllWsdls();
Assert.assertNotNull(wsdls);
Assert.assertEquals(wsdls.size(), 1);
}
use of org.wso2.carbon.apimgt.api.model.Wsdl in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testUploadWsdl.
@Test
public void testUploadWsdl() throws RegistryException, APIManagementException {
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
Resource resource = new ResourceImpl();
String resourcePath = "/test/wsdl";
String wsdlContent = "sample wsdl";
Resource resourceMock = Mockito.mock(Resource.class);
resourceMock.setContent(wsdlContent);
resourceMock.setMediaType(String.valueOf(ContentType.APPLICATION_XML));
Mockito.when(registry.newResource()).thenReturn(resource);
Mockito.doThrow(RegistryException.class).doReturn(resourcePath).when(registry).put(resourcePath, resource);
try {
abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
Assert.fail("Exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Error while uploading wsdl to from the registry"));
}
abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
Mockito.verify(registry, Mockito.atLeastOnce()).put(resourcePath, resource);
}
use of org.wso2.carbon.apimgt.api.model.Wsdl 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.api.model.Wsdl in project carbon-apimgt by wso2.
the class APIProviderImpl method updateApiArtifact.
private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
// Validate Transports
validateAndSetTransports(api);
validateAndSetAPISecurity(api);
boolean transactionCommitted = false;
String apiUUID = null;
try {
registry.beginTransaction();
String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
Resource apiResource = registry.get(artifact.getPath());
String oldAccessControlRoles = api.getAccessControlRoles();
if (apiResource != null) {
oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
}
GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
if (oldTags != null) {
for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
registry.removeTag(artifactPath, tag.getTagName());
}
}
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
// If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
// will skip registry update. Only if this API created with WSDL end point type we need to update
// wsdls for each update.
// check for wsdl endpoint
org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
String wsdlURL;
if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
String path = APIUtil.createWSDL(registry, api);
if (path != null) {
// reset the wsdl path to permlink
updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
}
}
}
}
artifactManager.updateGenericArtifact(updateApiArtifact);
// write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
// to gain performance
String apiStatus = api.getStatus().toUpperCase();
saveAPIStatus(artifactPath, apiStatus);
String[] visibleRoles = new String[0];
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
// propagate api status change and access control roles change to document artifact
String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
if (updatePermissions) {
APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
registry.commitTransaction();
transactionCommitted = true;
apiUUID = updateApiArtifact.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) {
// Retain the docs
List<Documentation> docs = getAllDocumentation(api.getId());
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 {
// In order to support content search feature - we need to update resource permissions of document resources
// if their visibility is set to API level.
List<Documentation> docs = getAllDocumentation(api.getId());
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);
}
}
}
}
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error from this level will mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
handleException("Error while performing registry transaction operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
handleException("Error occurred while rolling back the transaction.", ex);
}
}
return apiUUID;
}
Aggregations