use of org.wso2.carbon.apimgt.api.model.APIIdentifier 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.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImpl method addAPIRevision.
/**
* Adds a new APIRevision to an existing API
*
* @param apiRevision APIRevision
* @throws APIManagementException if failed to add APIRevision
*/
@Override
public String addAPIRevision(APIRevision apiRevision, String organization) throws APIManagementException {
int revisionCountPerAPI = apiMgtDAO.getRevisionCountByAPI(apiRevision.getApiUUID());
int maxRevisionCount = getMaxRevisionCount(organization);
if (revisionCountPerAPI >= maxRevisionCount) {
String errorMessage = "Maximum number of revisions per API has reached. " + "Need to remove stale revision to create a new Revision for API with API UUID:" + apiRevision.getApiUUID();
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED, apiRevision.getApiUUID()));
}
int revisionId = apiMgtDAO.getMostRecentRevisionId(apiRevision.getApiUUID()) + 1;
apiRevision.setId(revisionId);
APIIdentifier apiId = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
if (apiId == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiRevision.getApiUUID(), ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevision.getApiUUID()));
}
apiId.setUuid(apiRevision.getApiUUID());
String revisionUUID;
try {
revisionUUID = apiPersistenceInstance.addAPIRevision(new Organization(organization), apiId.getUUID(), revisionId);
} catch (APIPersistenceException e) {
String errorMessage = "Failed to add revision registry artifacts";
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_CREATING_API_REVISION, apiRevision.getApiUUID()));
}
if (StringUtils.isEmpty(revisionUUID)) {
String errorMessage = "Failed to retrieve revision uuid";
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
}
apiRevision.setRevisionUUID(revisionUUID);
apiMgtDAO.addAPIRevision(apiRevision);
if (importExportAPI != null) {
try {
File artifact = importExportAPI.exportAPI(apiRevision.getApiUUID(), revisionUUID, true, ExportFormat.JSON, false, true, organization);
// Keeping the organization as tenant domain since MG does not support organization-wise deployment
// Artifacts will be deployed in ST for all organizations
gatewayArtifactsMgtDAO.addGatewayAPIArtifactAndMetaData(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, APIConstants.HTTP_PROTOCOL, artifact);
if (artifactSaver != null) {
// Keeping the organization as tenant domain since MG does not support organization-wise deployment
// Artifacts will be deployed in ST for all organizations
artifactSaver.saveArtifact(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, artifact);
}
} catch (APIImportExportException | ArtifactSynchronizerException e) {
throw new APIManagementException("Error while Store the Revision Artifact", ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
}
}
return revisionUUID;
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPIbyUUID.
@Override
public API getAPIbyUUID(String uuid, String organization) throws APIManagementException {
Organization org = new Organization(organization);
try {
PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, uuid);
if (publisherAPI != null) {
API api = APIMapper.INSTANCE.toApi(publisherAPI);
APIIdentifier apiIdentifier = api.getId();
apiIdentifier.setUuid(uuid);
api.setId(apiIdentifier);
checkAccessControlPermission(userNameWithoutChange, api.getAccessControl(), api.getAccessControlRoles());
// ///////////////// Do processing on the data object//////////
populateRevisionInformation(api, uuid);
populateAPIInformation(uuid, organization, api);
loadMediationPoliciesToAPI(api, organization);
populateAPIStatus(api);
populateDefaultVersion(api);
return api;
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (APIPersistenceException e) {
throw new APIManagementException("Failed to get API", e);
} catch (OASPersistenceException e) {
throw new APIManagementException("Error while retrieving the OAS definition", e);
} catch (ParseException e) {
throw new APIManagementException("Error while parsing the OAS definition", e);
} catch (AsyncSpecPersistenceException e) {
throw new APIManagementException("Error while retrieving the Async API definition", e);
}
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImpl method copySequencesToNewVersion.
private void copySequencesToNewVersion(API api, String newVersion, String pathFlow) throws Exception {
String seqFilePath = APIUtil.getSequencePath(api.getId(), pathFlow);
if (registry.resourceExists(seqFilePath)) {
APIIdentifier newApiId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), newVersion);
String seqNewFilePath = APIUtil.getSequencePath(newApiId, pathFlow);
org.wso2.carbon.registry.api.Collection seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(seqFilePath);
if (seqCollection != null) {
String[] seqChildPaths = seqCollection.getChildren();
for (String seqChildPath : seqChildPaths) {
Resource sequence = registry.get(seqChildPath);
ResourceFile seqFile = new ResourceFile(sequence.getContentStream(), sequence.getMediaType());
OMElement seqElement = APIUtil.buildOMElement(sequence.getContentStream());
String seqFileName = seqElement.getAttributeValue(new QName("name"));
addResourceFile(api.getId(), seqNewFilePath + seqFileName, seqFile);
}
}
}
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImpl method undeployAPIRevisionDeployment.
/**
* Remove a new APIRevisionDeployment to an existing API
*
* @param apiId API UUID
* @param apiRevisionId API Revision UUID
* @param apiRevisionDeployments List of APIRevisionDeployment objects
* @param organization
* @throws APIManagementException if failed to add APIRevision
*/
@Override
public void undeployAPIRevisionDeployment(String apiId, String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeployments, String organization) throws APIManagementException {
APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiId);
if (apiIdentifier == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId);
if (apiRevision == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_REVISION_NOT_FOUND, apiRevisionId));
}
API api = getAPIbyUUID(apiId, apiRevision, organization);
removeFromGateway(api, new HashSet<>(apiRevisionDeployments), Collections.emptySet());
apiMgtDAO.removeAPIRevisionDeployment(apiRevisionId, apiRevisionDeployments);
GatewayArtifactsMgtDAO.getInstance().removePublishedGatewayLabels(apiId, apiRevisionId);
}
Aggregations