use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class APIManagerConfigurationTest method testEnvironmentsConfigWithAdditionalProperties.
@Test
public void testEnvironmentsConfigWithAdditionalProperties() throws XMLStreamException, APIManagementException {
String envConfig = "<Environment type=\"hybrid\" api-console=\"true\" isDefault=\"true\">\n" + " <Name>Default</Name>\n" + " <DisplayName></DisplayName>\n" + " <Description>This is a hybrid gateway that handles both production and sandbox token traffic.</Description>\n" + " <!-- Server URL of the API gateway -->\n" + " <ServerURL>https://localhost:9440/services/</ServerURL>\n" + " <!-- Admin username for the API gateway. -->\n" + " <Username>${admin.username}</Username>\n" + " <!-- Admin password for the API gateway.-->\n" + " <Password>${admin.password}</Password>\n" + " <!-- Provider Vendor of the API gateway.-->\n" + " <Provider>wso2</Provider>\n" + " <!-- Endpoint URLs for the APIs hosted in this API gateway.-->\n" + " <GatewayEndpoint>https://localhost:9440,http://localhost:9440</GatewayEndpoint>\n" + " <!-- Additional properties for External Gateways -->\n" + " <!-- Endpoint URLs of the WebSocket APIs hosted in this API Gateway -->\n" + " <GatewayWSEndpoint>ws://localhost:9099,wss://localhost:8099</GatewayWSEndpoint>\n" + " <!-- Endpoint URLs of the WebSub APIs hosted in this API Gateway -->\n" + " <GatewayWebSubEndpoint>http://localhost:9021,https://localhost:8021</GatewayWebSubEndpoint>\n" + " <Properties>\n" + " <Property name=\"Organization\">WSO2</Property>\n" + " <Property name=\"DisplayName\">Development Environment</Property>\n" + " <Property name=\"DevAccountName\">dev-1</Property>\n" + " </Properties>\n" + " <VirtualHosts>\n" + " </VirtualHosts>\n" + " </Environment>";
OMElement element = AXIOMUtil.stringToOM(envConfig);
APIManagerConfiguration config = new APIManagerConfiguration();
config.setEnvironmentConfig(element);
Map<String, Environment> environmentsList = config.getGatewayEnvironments();
Assert.assertFalse(environmentsList.isEmpty());
Environment defaultEnv = environmentsList.get("Default");
Assert.assertFalse(defaultEnv.getAdditionalProperties().isEmpty());
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIProductForStateChange.
/**
* Update API Product in registry for lifecycle state change
*
* @param apiProduct API Product Object
* @param currentStatus Current state of API Product
* @param newStatus New state of API Product
* @return boolean indicates success or failure
* @throws APIManagementException if there is an error when updating API Product for lifecycle state
* @throws FaultGatewaysException if there is an error when updating API Product for lifecycle state
*/
public void updateAPIProductForStateChange(APIProduct apiProduct, String currentStatus, String newStatus) throws APIManagementException, FaultGatewaysException {
String provider = apiProduct.getId().getProviderName();
boolean isTenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
if (!currentStatus.equals(newStatus)) {
apiProduct.setState(newStatus);
// If API status changed to publish we should add it to recently added APIs list
// this should happen in store-publisher cluster domain if deployment is distributed
// IF new API published we will add it to recently added APIs
Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).removeAll();
if (APIConstants.RETIRED.equals(newStatus)) {
cleanUpPendingSubscriptionCreationProcessesByAPI(apiProduct.getUuid());
apiMgtDAO.removeAllSubscriptions(apiProduct.getUuid());
deleteAPIProductRevisions(apiProduct.getUuid(), tenantDomain);
}
PublisherAPIProduct publisherAPIProduct = APIProductMapper.INSTANCE.toPublisherApiProduct(apiProduct);
try {
apiPersistenceInstance.updateAPIProduct(new Organization(apiProduct.getOrganization()), publisherAPIProduct);
} catch (APIPersistenceException e) {
handleException("Error while persisting the updated API Product", e);
}
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization 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.Organization in project carbon-apimgt by wso2.
the class APIProviderImpl method deleteAPIProduct.
public void deleteAPIProduct(APIProduct apiProduct) throws APIManagementException {
APIProductIdentifier identifier = apiProduct.getId();
try {
// int apiId = apiMgtDAO.getAPIID(identifier, null);
long subsCount = apiMgtDAO.getAPISubscriptionCountByAPI(identifier);
if (subsCount > 0) {
// Logging as a WARN since this isn't an error scenario.
String message = "Cannot remove the API Product as active subscriptions exist.";
log.warn(message);
throw new APIManagementException(message);
}
// gatewayType check is required when API Management is deployed on
// other servers to avoid synapse
deleteAPIProductRevisions(apiProduct.getUuid(), apiProduct.getOrganization());
apiPersistenceInstance.deleteAPIProduct(new Organization(apiProduct.getOrganization()), apiProduct.getUuid());
apiMgtDAO.deleteAPIProduct(identifier);
cleanUpPendingAPIStateChangeTask(apiProduct.getProductId(), true);
if (log.isDebugEnabled()) {
String logMessage = "API Product Name: " + identifier.getName() + ", API Product Version " + identifier.getVersion() + " successfully removed from the database.";
log.debug(logMessage);
}
JSONObject apiLogObject = new JSONObject();
apiLogObject.put(APIConstants.AuditLogConstants.NAME, identifier.getName());
apiLogObject.put(APIConstants.AuditLogConstants.VERSION, identifier.getVersion());
apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API_PRODUCT, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiProduct.getUuid());
} catch (APIPersistenceException e) {
handleException("Failed to remove the API product", e);
} catch (WorkflowException e) {
handleException("Error while removing the pending workflows of API Product", e);
}
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class APIProviderImpl method calculateVersionTimestamp.
private String calculateVersionTimestamp(String provider, String name, String version, String org) throws APIManagementException {
if (StringUtils.isEmpty(provider) || StringUtils.isEmpty(name) || StringUtils.isEmpty(org)) {
throw new APIManagementException("Invalid API information, name=" + name + " provider=" + provider + " organization=" + org);
}
TreeMap<String, API> apiSortedMap = new TreeMap<>();
List<API> apiList = getAPIVersionsByProviderAndName(provider, name, org);
for (API mappedAPI : apiList) {
apiSortedMap.put(mappedAPI.getVersionTimestamp(), mappedAPI);
}
APIVersionStringComparator comparator = new APIVersionStringComparator();
String latestVersion = version;
long previousTimestamp = 0L;
String latestTimestamp = "";
for (API tempAPI : apiSortedMap.values()) {
if (comparator.compare(tempAPI.getId().getVersion(), latestVersion) > 0) {
latestTimestamp = String.valueOf((previousTimestamp + Long.valueOf(tempAPI.getVersionTimestamp())) / 2);
break;
} else {
previousTimestamp = Long.valueOf(tempAPI.getVersionTimestamp());
}
}
if (StringUtils.isEmpty(latestTimestamp)) {
latestTimestamp = String.valueOf(System.currentTimeMillis());
}
return latestTimestamp;
}
Aggregations