use of org.wso2.carbon.apimgt.core.models.APIResource in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method generateCompositeApiFromSwaggerResource.
@Override
public CompositeAPI.Builder generateCompositeApiFromSwaggerResource(String provider, String apiDefinition) throws APIManagementException {
SwaggerParser swaggerParser = new SwaggerParser();
Swagger swagger = swaggerParser.parse(apiDefinition);
if (swagger == null) {
throw new APIManagementException("Swagger could not be generated from provided API definition");
}
Info apiInfo = swagger.getInfo();
if (apiInfo == null) {
throw new APIManagementException("Provided Swagger definition doesn't contain API information");
} else {
String apiName = apiInfo.getTitle();
String apiVersion = apiInfo.getVersion();
String apiDescription = apiInfo.getDescription();
CompositeAPI.Builder apiBuilder = new CompositeAPI.Builder().provider(provider).name(apiName).version(apiVersion).description(apiDescription).context(swagger.getBasePath());
List<APIResource> apiResourceList = parseSwaggerAPIResources(new StringBuilder(apiDefinition));
Map<String, UriTemplate> uriTemplateMap = new HashMap();
for (APIResource apiResource : apiResourceList) {
uriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
}
apiBuilder.uriTemplates(uriTemplateMap);
apiBuilder.id(UUID.randomUUID().toString());
return apiBuilder;
}
}
use of org.wso2.carbon.apimgt.core.models.APIResource in project carbon-apimgt by wso2.
the class PublisherCommonUtils method getRemovedProductResources.
/**
* Finds resources that have been removed in the updated API, that are currently reused by API Products.
*
* @param updatedDTO Updated API
* @param existingAPI Existing API
* @return List of removed resources that are reused among API Products
*/
private static List<APIResource> getRemovedProductResources(APIDTO updatedDTO, API existingAPI) {
List<APIOperationsDTO> updatedOperations = updatedDTO.getOperations();
Set<URITemplate> existingUriTemplates = existingAPI.getUriTemplates();
List<APIResource> removedReusedResources = new ArrayList<>();
for (URITemplate existingUriTemplate : existingUriTemplates) {
// If existing URITemplate is used by any API Products
if (!existingUriTemplate.retrieveUsedByProducts().isEmpty()) {
String existingVerb = existingUriTemplate.getHTTPVerb();
String existingPath = existingUriTemplate.getUriTemplate();
boolean isReusedResourceRemoved = true;
for (APIOperationsDTO updatedOperation : updatedOperations) {
String updatedVerb = updatedOperation.getVerb();
String updatedPath = updatedOperation.getTarget();
// Check if existing reused resource is among updated resources
if (existingVerb.equalsIgnoreCase(updatedVerb) && existingPath.equalsIgnoreCase(updatedPath)) {
isReusedResourceRemoved = false;
break;
}
}
// Existing reused resource is not among updated resources
if (isReusedResourceRemoved) {
APIResource removedResource = new APIResource(existingVerb, existingPath);
removedReusedResources.add(removedResource);
}
}
}
return removedReusedResources;
}
use of org.wso2.carbon.apimgt.core.models.APIResource in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateApi.
/**
* Update an API.
*
* @param originalAPI Existing API
* @param apiDtoToUpdate New API DTO to update
* @param apiProvider API Provider
* @param tokenScopes Scopes of the token
* @throws ParseException If an error occurs while parsing the endpoint configuration
* @throws CryptoException If an error occurs while encrypting the secret key of API
* @throws APIManagementException If an error occurs while updating the API
* @throws FaultGatewaysException If an error occurs while updating manage of an existing API
*/
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
APIIdentifier apiIdentifier = originalAPI.getId();
// Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
if (tokenScopes == null) {
throw new APIManagementException("Error occurred while updating the API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
}
boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
JSONParser parser = new JSONParser();
String oldEndpointConfigString = originalAPI.getEndpointConfig();
JSONObject oldEndpointConfig = null;
if (StringUtils.isNotBlank(oldEndpointConfigString)) {
oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
}
String oldProductionApiSecret = null;
String oldSandboxApiSecret = null;
if (oldEndpointConfig != null) {
if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
}
}
}
}
Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
// AWS Lambda: secret key encryption while updating the API
if (apiDtoToUpdate.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
} else {
JSONParser jsonParser = new JSONParser();
JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDtoToUpdate.setEndpointConfig(endpointConfig);
}
}
}
}
if (!hasClassLevelScope) {
// Validate per-field scopes
apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
}
// API Name change not allowed if OnPrem
if (APIUtil.isOnPremResolver()) {
apiDtoToUpdate.setName(apiIdentifier.getApiName());
}
apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
}
// Validate API Security
List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
// validation for tiers
List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
String originalStatus = originalAPI.getStatus();
if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
}
}
if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
}
if (apiDtoToUpdate.getAccessControlRoles() != null) {
String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getVisibleRoles() != null) {
String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (apiDtoToUpdate.getAdditionalProperties() != null) {
String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
}
}
// Validate if resources are empty
if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
}
apiToUpdate.setUUID(originalAPI.getUUID());
apiToUpdate.setOrganization(originalAPI.getOrganization());
validateScopes(apiToUpdate);
apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
if (apiDtoToUpdate.getKeyManagers() instanceof List) {
apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
} else {
apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
}
if (!isAsyncAPI) {
String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
SwaggerData swaggerData = new SwaggerData(apiToUpdate);
String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
if (!isGraphql) {
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
// set operation policies from the original API Payload
Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
for (URITemplate uriTemplate : uriTemplatesFromPayload) {
if (!uriTemplate.getOperationPolicies().isEmpty()) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
}
}
for (URITemplate uriTemplate : uriTemplates) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (operationPoliciesPerURITemplate.containsKey(key)) {
uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
}
}
apiToUpdate.setUriTemplates(uriTemplates);
}
} else {
String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
AsyncApiParser asyncApiParser = new AsyncApiParser();
String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
}
apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
// validate API categories
List<APICategory> apiCategories = apiToUpdate.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(originalAPI.getOrganization());
apiCategoriesList.add(category);
}
apiToUpdate.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
apiToUpdate.setOrganization(originalAPI.getOrganization());
apiProvider.updateAPI(apiToUpdate, originalAPI);
return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
use of org.wso2.carbon.apimgt.core.models.APIResource in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method updateAPI.
@SuppressWarnings("unchecked")
@Override
public PublisherAPI updateAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
API api = APIMapper.INSTANCE.toApi(publisherAPI);
boolean transactionCommitted = false;
boolean tenantFlowStarted = false;
Registry registry = null;
try {
RegistryHolder holder = getRegistry(org.getName());
registry = holder.getRegistry();
tenantFlowStarted = holder.isTenantFlowStarted();
registry.beginTransaction();
String apiArtifactId = registry.get(RegistryPersistenceUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifact artifact = getAPIArtifact(apiArtifactId, registry);
boolean isSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED));
boolean isDigestSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST));
String userName = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME);
String password = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD);
if (!isSecured && !isDigestSecured && userName != null) {
api.setEndpointUTUsername(userName);
api.setEndpointUTPassword(password);
}
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 = RegistryPersistenceUtil.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);
}
}
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(registry, 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)) {
RegistryPersistenceUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
RegistryPersistenceUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
RegistryPersistenceUtil.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());
}
}
if (api.getSwaggerDefinition() != null) {
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(api.getSwaggerDefinition());
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
}
// doc visibility change
String apiOrAPIProductDocPath = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
if (registry.resourceExists(apiOrAPIProductDocPath)) {
Resource resource = registry.get(apiOrAPIProductDocPath);
if (resource instanceof org.wso2.carbon.registry.core.Collection) {
String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
for (String docPath : docsPaths) {
if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
Resource docResource = registry.get(docPath);
GenericArtifactManager docArtifactManager = RegistryPersistenceDocUtil.getDocumentArtifactManager(registry);
GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + doc.getName();
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + doc.getName();
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = RegistryPersistenceDocUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
}
}
}
setSoapToRestSequences(publisherAPI, registry);
registry.commitTransaction();
transactionCommitted = true;
return APIMapper.INSTANCE.toPublisherApi(api);
} 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);
}
throw new APIPersistenceException("Error while performing registry transaction operation ", e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
throw new APIPersistenceException("Error occurred while rolling back the transaction. ", ex);
}
}
}
use of org.wso2.carbon.apimgt.core.models.APIResource in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method searchPaginatedPublisherAPIs.
private PublisherAPISearchResult searchPaginatedPublisherAPIs(Registry userRegistry, int tenantIDLocal, String searchQuery, int start, int offset) throws APIManagementException {
int totalLength = 0;
PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
try {
final int maxPaginationLimit = getMaxPaginationLimit();
PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
totalLength = PaginationContext.getInstance().getLength();
boolean isFound = true;
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
isFound = false;
}
} else {
isFound = false;
}
}
if (!isFound) {
return searchResults;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// Remove the additional 1 added earlier when setting max pagination limit
--totalLength;
}
List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
int tempLength = 0;
for (GovernanceArtifact artifact : governanceArtifacts) {
PublisherAPIInfo apiInfo = new PublisherAPIInfo();
String artifactPath = GovernanceUtils.getArtifactPath(userRegistry, artifact.getId());
Resource apiResource = userRegistry.get(artifactPath);
apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
apiInfo.setId(artifact.getId());
apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
apiInfo.setStatus(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
apiInfo.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
apiInfo.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
apiInfo.setUpdatedTime(apiResource.getLastModified());
apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
publisherAPIInfoList.add(apiInfo);
// Ensure the APIs returned matches the length, there could be an additional API
// returned due incrementing the pagination limit when getting from registry
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
// Sort the publisherAPIInfoList according to the API name.
Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
searchResults.setTotalAPIsCount(totalLength);
} catch (RegistryException e) {
String msg = "Failed to search APIs with type";
throw new APIManagementException(msg, e);
} finally {
PaginationContext.destroy();
}
return searchResults;
}
Aggregations