use of org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException in project carbon-apimgt by wso2.
the class ImportUtils method importApi.
/**
* This method imports an API.
*
* @param extractedFolderPath Location of the extracted folder of the API
* @param importedApiDTO API DTO of the importing API
* (This will not be null when importing dependent APIs with API Products)
* @param preserveProvider Decision to keep or replace the provider
* @param overwrite Whether to update the API or not
* @param tokenScopes Scopes of the token
* @param dependentAPIParamsConfigObject Params configuration of an API (this will not be null if a dependent API
* of an
* API product wants to override the parameters)
* @param organization Identifier of an Organization
* @throws APIImportExportException If there is an error in importing an API
* @@return Imported API
*/
public static API importApi(String extractedFolderPath, APIDTO importedApiDTO, Boolean preserveProvider, Boolean rotateRevision, Boolean overwrite, Boolean dependentAPIFromProduct, String[] tokenScopes, JsonObject dependentAPIParamsConfigObject, String organization) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
APIDefinitionValidationResponse validationResponse = null;
String graphQLSchema = null;
API importedApi = null;
String currentStatus;
String targetStatus;
String lifecycleAction;
GraphqlComplexityInfo graphqlComplexityInfo = null;
int tenantId = 0;
JsonArray deploymentInfoArray = null;
JsonObject paramsConfigObject;
try {
if (importedApiDTO == null) {
JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API);
importedApiDTO = new Gson().fromJson(jsonObject, APIDTO.class);
}
// If the provided dependent APIs params config is null, it means this happening when importing an API (not
// because when importing a dependent API of an API Product). Hence, try to retrieve the definition from
// the API folder path
paramsConfigObject = (dependentAPIParamsConfigObject != null) ? dependentAPIParamsConfigObject : APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
// If above the params configurations are not null, then resolve those
if (paramsConfigObject != null) {
importedApiDTO = APIControllerUtil.injectEnvParamsToAPI(importedApiDTO, paramsConfigObject, extractedFolderPath);
if (!isAdvertiseOnlyAPI(importedApiDTO)) {
JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
deploymentInfoArray = deploymentsParam.getAsJsonArray();
}
}
}
String apiType = importedApiDTO.getType().toString();
APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiDTO.getProvider());
// Validate swagger content except for streaming APIs
if (!PublisherCommonUtils.isStreamingAPI(importedApiDTO) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
validationResponse = retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
}
// Validate the GraphQL schema
if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
graphQLSchema = retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
}
// Validate the WSDL of SOAP APIs
if (APIConstants.API_TYPE_SOAP.equalsIgnoreCase(apiType)) {
validateWSDLFromArchive(extractedFolderPath, importedApiDTO);
}
// Validate the AsyncAPI definition of streaming APIs
if (PublisherCommonUtils.isStreamingAPI(importedApiDTO)) {
validationResponse = retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
}
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
// The status of the importing API should be stored separately to do the lifecycle change at the end
targetStatus = importedApiDTO.getLifeCycleStatus();
API targetApi = retrieveApiToOverwrite(importedApiDTO.getName(), importedApiDTO.getVersion(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
if (isAdvertiseOnlyAPI(importedApiDTO)) {
processAdvertiseOnlyPropertiesInDTO(importedApiDTO, tokenScopes);
}
Map<String, List<OperationPolicy>> extractedPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(importedApiDTO.getOperations());
// If the overwrite is set to true (which means an update), retrieve the existing API
if (Boolean.TRUE.equals(overwrite) && targetApi != null) {
log.info("Existing API found, attempting to update it...");
currentStatus = targetApi.getStatus();
// Set the status of imported API to current status of target API when updating
importedApiDTO.setLifeCycleStatus(currentStatus);
// when updating an API from the UI there is at least one resource (operation) inside the DTO.
if (importedApiDTO.getOperations().isEmpty()) {
setOperationsToDTO(importedApiDTO, validationResponse);
}
targetApi.setOrganization(organization);
importedApi = PublisherCommonUtils.updateApi(targetApi, importedApiDTO, RestApiCommonUtil.getLoggedInUserProvider(), tokenScopes);
} else {
if (targetApi == null && Boolean.TRUE.equals(overwrite)) {
log.info("Cannot find : " + importedApiDTO.getName() + "-" + importedApiDTO.getVersion() + ". Creating it.");
}
// Initialize to CREATED when import
currentStatus = APIStatus.CREATED.toString();
importedApiDTO.setLifeCycleStatus(currentStatus);
importedApi = PublisherCommonUtils.addAPIWithGeneratedSwaggerDefinition(importedApiDTO, ImportExportConstants.OAS_VERSION_3, importedApiDTO.getProvider(), organization);
// Set API definition to validationResponse if the API is imported with sample API definition
if (validationResponse.isInit()) {
validationResponse.setContent(importedApi.getSwaggerDefinition());
validationResponse.setJsonContent(importedApi.getSwaggerDefinition());
}
}
if (!extractedPoliciesMap.isEmpty()) {
importedApi.setUriTemplates(validateOperationPolicies(importedApi, apiProvider, extractedFolderPath, extractedPoliciesMap, currentTenantDomain));
apiProvider.updateAPI(importedApi);
}
// Retrieving the life cycle action to do the lifecycle state change explicitly later
lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
// Add/update swagger content except for streaming APIs and GraphQL APIs
if (!PublisherCommonUtils.isStreamingAPI(importedApiDTO) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
// Add the validated swagger separately since the UI does the same procedure
PublisherCommonUtils.updateSwagger(importedApi.getUuid(), validationResponse, false, organization);
}
// Add the GraphQL schema
if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
importedApi.setOrganization(organization);
PublisherCommonUtils.addGraphQLSchema(importedApi, graphQLSchema, apiProvider);
graphqlComplexityInfo = retrieveGraphqlComplexityInfoFromArchive(extractedFolderPath, graphQLSchema);
if (graphqlComplexityInfo != null && graphqlComplexityInfo.getList().size() != 0) {
apiProvider.addOrUpdateComplexityDetails(importedApi.getUuid(), graphqlComplexityInfo);
}
}
// Add/update Async API definition for streaming APIs
if (PublisherCommonUtils.isStreamingAPI(importedApiDTO)) {
// Add the validated Async API definition separately since the UI does the same procedure
PublisherCommonUtils.updateAsyncAPIDefinition(importedApi.getUuid(), validationResponse, organization);
}
tenantId = APIUtil.getTenantId(RestApiCommonUtil.getLoggedInUsername());
// Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in
// implementation
ApiTypeWrapper apiTypeWrapperWithUpdatedApi = new ApiTypeWrapper(importedApi);
addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider);
addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider, organization);
addAPIWsdl(extractedFolderPath, importedApi, apiProvider);
if (StringUtils.equals(importedApi.getType().toLowerCase(), APIConstants.API_TYPE_SOAPTOREST.toLowerCase())) {
addSOAPToREST(importedApi, validationResponse.getContent(), apiProvider);
}
if (!isAdvertiseOnlyAPI(importedApiDTO)) {
addAPISequences(extractedFolderPath, importedApi, apiProvider);
addAPISpecificSequences(extractedFolderPath, importedApi, apiProvider);
addEndpointCertificates(extractedFolderPath, importedApi, apiProvider, tenantId);
if (log.isDebugEnabled()) {
log.debug("Mutual SSL enabled. Importing client certificates.");
}
addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApi.getId().getProviderName(), organization);
}
// Change API lifecycle if state transition is required
if (StringUtils.isNotEmpty(lifecycleAction)) {
apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
if (StringUtils.equals(lifecycleAction, APIConstants.LC_PUBLISH_LC_STATE)) {
apiProvider.changeAPILCCheckListItems(importedApi.getId(), ImportExportConstants.REFER_REQUIRE_RE_SUBSCRIPTION_CHECK_ITEM, true);
}
apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApi), lifecycleAction, new HashMap<>());
}
importedApi.setStatus(targetStatus);
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
if (deploymentInfoArray == null && !isAdvertiseOnlyAPI(importedApiDTO)) {
// If the params have not overwritten the deployment environments, yaml file will be read
deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, dependentAPIFromProduct);
}
List<APIRevisionDeployment> apiRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, tenantDomain, apiProvider, organization);
if (apiRevisionDeployments.size() > 0) {
String importedAPIUuid = importedApi.getUuid();
String revisionId;
APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(importedAPIUuid);
apiRevision.setDescription("Revision created after importing the API");
try {
revisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
if (log.isDebugEnabled()) {
log.debug("A new revision has been created for API " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion());
}
} catch (APIManagementException e) {
// enabled, earliest revision will be deleted before creating a revision again
if (e.getErrorHandler().getErrorCode() == ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED).getErrorCode() && rotateRevision) {
String earliestRevisionUuid = apiProvider.getEarliestRevisionUUID(importedAPIUuid);
List<APIRevisionDeployment> deploymentsList = apiProvider.getAPIRevisionDeploymentList(earliestRevisionUuid);
// if the earliest revision is already deployed in gateway environments, it will be undeployed
// before deleting
apiProvider.undeployAPIRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList, organization);
apiProvider.deleteAPIRevision(importedAPIUuid, earliestRevisionUuid, tenantDomain);
revisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
if (log.isDebugEnabled()) {
log.debug("Revision ID: " + earliestRevisionUuid + " has been undeployed from " + deploymentsList.size() + " gateway environments and created a new revision ID: " + revisionId + " for API " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion());
}
} else {
throw new APIManagementException("Error occurred while creating a new revision for the API: " + importedApi.getId().getApiName(), e);
}
}
// Once the new revision successfully created, artifacts will be deployed in mentioned gateway
// environments
apiProvider.deployAPIRevision(importedAPIUuid, revisionId, apiRevisionDeployments, organization);
if (log.isDebugEnabled()) {
log.debug("API: " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion() + " was deployed in " + apiRevisionDeployments.size() + " gateway environments.");
}
} else {
log.info("Valid deployment environments were not found for the imported artifact. Only working copy " + "was updated and not deployed in any of the gateway environments.");
}
return importedApi;
} catch (CryptoException | IOException e) {
throw new APIManagementException("Error while reading API meta information from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA);
} catch (FaultGatewaysException e) {
throw new APIManagementException("Error while updating API: " + importedApi.getId().getApiName(), e);
} catch (APIMgtAuthorizationFailedException e) {
throw new APIManagementException("Please enable preserveProvider property for cross tenant API Import.", e, ExceptionCodes.TENANT_MISMATCH);
} catch (ParseException e) {
throw new APIManagementException("Error while parsing the endpoint configuration of the API", ExceptionCodes.JSON_PARSE_ERROR);
} catch (APIManagementException e) {
String errorMessage = "Error while importing API: ";
if (importedApi != null) {
errorMessage += importedApi.getId().getApiName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApi.getId().getVersion();
}
throw new APIManagementException(errorMessage + StringUtils.SPACE + e.getMessage(), e);
}
}
use of org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsSubscriptionIdPut.
/**
* Update already created subscriptions with the details specified in the body parameter
*
* @param body new subscription details
* @return newly added subscription as a SubscriptionDTO if successful
*/
@Override
public Response subscriptionsSubscriptionIdPut(String subscriptionId, SubscriptionDTO body, String xWSO2Tenant, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer;
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
apiConsumer = RestApiCommonUtil.getConsumer(username);
String applicationId = body.getApplicationId();
String currentThrottlingPolicy = body.getThrottlingPolicy();
String requestedThrottlingPolicy = body.getRequestedThrottlingPolicy();
SubscribedAPI subscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionId);
// Check whether the subscription status is not empty and also not blocked
if (body.getStatus() != null && subscribedAPI != null) {
if ("BLOCKED".equals(body.getStatus().value()) || "ON_HOLD".equals(body.getStatus().value()) || "REJECTED".equals(body.getStatus().value()) || "BLOCKED".equals(subscribedAPI.getSubStatus()) || "ON_HOLD".equals(subscribedAPI.getSubStatus()) || "REJECTED".equals(subscribedAPI.getSubStatus())) {
RestApiUtil.handleBadRequest("Cannot update subscriptions with provided or existing status", log);
return null;
}
} else {
RestApiUtil.handleBadRequest("Request must contain status of the subscription", log);
return null;
}
// this will throw a APIMgtResourceNotFoundException
if (body.getApiId() != null) {
if (!RestAPIStoreUtils.isUserAccessAllowedForAPIByUUID(body.getApiId(), organization)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, body.getApiId(), log);
}
} else {
RestApiUtil.handleBadRequest("Request must contain either apiIdentifier or apiProductIdentifier and the relevant type", log);
return null;
}
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
// required application not found
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
return null;
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
// application access failure occurred
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(body.getApiId(), organization);
apiTypeWrapper.setTier(body.getThrottlingPolicy());
SubscriptionResponse subscriptionResponse = apiConsumer.updateSubscription(apiTypeWrapper, username, application, subscriptionId, currentThrottlingPolicy, requestedThrottlingPolicy);
SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, organization);
WorkflowResponse workflowResponse = subscriptionResponse.getWorkflowResponse();
if (workflowResponse instanceof HttpWorkflowResponse) {
String payload = workflowResponse.getJSONPayload();
addedSubscriptionDTO.setRedirectionParams(payload);
}
return Response.ok(new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTIONS + "/" + addedSubscribedAPI.getUUID())).entity(addedSubscriptionDTO).build();
} catch (APIMgtAuthorizationFailedException e) {
// this occurs when the api:application:tier mapping is not allowed. The reason for the message is taken from
// the message of the exception e
RestApiUtil.handleAuthorizationFailure(e.getMessage(), e, log);
} catch (SubscriptionAlreadyExistingException e) {
RestApiUtil.handleResourceAlreadyExistsError("Specified subscription already exists for API " + body.getApiId() + ", for application " + body.getApplicationId(), e, log);
} catch (APIManagementException | URISyntaxException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
// this happens when the specified API identifier does not exist
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, body.getApiId(), e, log);
} else {
// unhandled exception
RestApiUtil.handleInternalServerError("Error while adding the subscription API:" + body.getApiId() + ", application:" + body.getApplicationId() + ", tier:" + body.getThrottlingPolicy(), e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException in project carbon-apimgt by wso2.
the class RestApiUtilTest method testIsDueToResourceNotFoundWithInvalidException.
@Test
public void testIsDueToResourceNotFoundWithInvalidException() throws Exception {
APIMgtAuthorizationFailedException testAPIMgtAuthorizationFailedException = new APIMgtAuthorizationFailedException("New Sample exception");
Throwable testThrowable = new Throwable();
PowerMockito.spy(RestApiUtil.class);
PowerMockito.doReturn(testAPIMgtAuthorizationFailedException).when(RestApiUtil.class, "getPossibleErrorCause", testThrowable);
Assert.assertFalse("Invalid exception has been passed.", RestApiUtil.isDueToResourceNotFound(testThrowable));
}
use of org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException in project carbon-apimgt by wso2.
the class APIConsumerImpl method checkSubscriptionAllowed.
/**
* Check if the specified subscription is allowed for the logged in user
*
* @param apiTypeWrapper Api Type wrapper that contains either an API or API Product
* @throws APIManagementException if the subscription allow check was failed. If the user is not allowed to add the
* subscription, this will throw an instance of APIMgtAuthorizationFailedException with the reason as the message
*/
private void checkSubscriptionAllowed(ApiTypeWrapper apiTypeWrapper) throws APIManagementException {
Set<Tier> tiers;
String subscriptionAvailability;
String subscriptionAllowedTenants;
if (apiTypeWrapper.isAPIProduct()) {
APIProduct product = apiTypeWrapper.getApiProduct();
tiers = product.getAvailableTiers();
subscriptionAvailability = product.getSubscriptionAvailability();
subscriptionAllowedTenants = product.getSubscriptionAvailableTenants();
} else {
API api = apiTypeWrapper.getApi();
String apiSecurity = api.getApiSecurity();
if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
String msg = "Subscription is not allowed for API " + apiTypeWrapper.toString() + ". To access the API, " + "please use the client certificate";
throw new APIMgtAuthorizationFailedException(msg);
}
tiers = api.getAvailableTiers();
subscriptionAvailability = api.getSubscriptionAvailability();
subscriptionAllowedTenants = api.getSubscriptionAvailableTenants();
}
String apiOrganization = apiTypeWrapper.getOrganization();
// Tenant based validation for subscription
boolean subscriptionAllowed = false;
if (!organization.equals(apiOrganization)) {
if (APIConstants.SUBSCRIPTION_TO_ALL_TENANTS.equals(subscriptionAvailability)) {
subscriptionAllowed = true;
} else if (APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS.equals(subscriptionAvailability)) {
if (subscriptionAllowedTenants != null) {
String[] allowedTenants = subscriptionAllowedTenants.split(",");
for (String tenant : allowedTenants) {
if (tenant != null && tenantDomain.equals(tenant.trim())) {
subscriptionAllowed = true;
break;
}
}
}
}
} else {
subscriptionAllowed = true;
}
if (!subscriptionAllowed) {
throw new APIMgtAuthorizationFailedException("Subscription is not allowed for " + userNameWithoutChange);
}
// check whether the specified tier is within the allowed tiers for the API
Iterator<Tier> iterator = tiers.iterator();
boolean isTierAllowed = false;
List<String> allowedTierList = new ArrayList<>();
while (iterator.hasNext()) {
Tier t = iterator.next();
if (t.getName() != null && (t.getName()).equals(apiTypeWrapper.getTier())) {
isTierAllowed = true;
}
allowedTierList.add(t.getName());
}
if (!isTierAllowed) {
String msg = "Tier " + apiTypeWrapper.getTier() + " is not allowed for API/API Product " + apiTypeWrapper + ". Only " + Arrays.toString(allowedTierList.toArray()) + " Tiers are allowed.";
throw new APIManagementException(msg, ExceptionCodes.from(ExceptionCodes.SUBSCRIPTION_TIER_NOT_ALLOWED, apiTypeWrapper.getTier(), username));
}
}
use of org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsPost.
/**
* Creates a new subscriptions with the details specified in the body parameter
*
* @param body new subscription details
* @return newly added subscription as a SubscriptionDTO if successful
*/
@Override
public Response subscriptionsPost(SubscriptionDTO body, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer;
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String userOrganization = RestApiUtil.getValidatedSubjectOrganization(messageContext);
apiConsumer = RestApiCommonUtil.getConsumer(username, userOrganization);
String applicationId = body.getApplicationId();
// this will throw a APIMgtResourceNotFoundException
if (body.getApiId() != null) {
if (!RestAPIStoreUtils.isUserAccessAllowedForAPIByUUID(body.getApiId(), organization)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, body.getApiId(), log);
}
} else {
RestApiUtil.handleBadRequest("Request must contain either apiIdentifier or apiProductIdentifier and the relevant type", log);
return null;
}
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
// required application not found
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
return null;
}
// If application creation workflow status is pending or rejected, throw a Bad request exception
if (application.getStatus().equals(WorkflowStatus.REJECTED.toString()) || application.getStatus().equals(WorkflowStatus.CREATED.toString())) {
RestApiUtil.handleBadRequest("Workflow status is not Approved", log);
return null;
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
// application access failure occurred
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(body.getApiId(), organization);
apiTypeWrapper.setTier(body.getThrottlingPolicy());
SubscriptionResponse subscriptionResponse = apiConsumer.addSubscription(apiTypeWrapper, username, application);
SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, apiTypeWrapper, organization);
WorkflowResponse workflowResponse = subscriptionResponse.getWorkflowResponse();
if (workflowResponse instanceof HttpWorkflowResponse) {
String payload = workflowResponse.getJSONPayload();
addedSubscriptionDTO.setRedirectionParams(payload);
}
return Response.created(new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTIONS + "/" + addedSubscribedAPI.getUUID())).entity(addedSubscriptionDTO).build();
} catch (APIMgtAuthorizationFailedException e) {
// this occurs when the api:application:tier mapping is not allowed. The reason for the message is taken from
// the message of the exception e
RestApiUtil.handleAuthorizationFailure(e.getMessage(), e, log);
} catch (SubscriptionAlreadyExistingException e) {
RestApiUtil.handleResourceAlreadyExistsError("Specified subscription already exists for API " + body.getApiId() + ", for application " + body.getApplicationId(), e, log);
} catch (URISyntaxException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
// this happens when the specified API identifier does not exist
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, body.getApiId(), e, log);
} else {
// unhandled exception
RestApiUtil.handleInternalServerError("Error while adding the subscription API:" + body.getApiId() + ", application:" + body.getApplicationId() + ", tier:" + body.getThrottlingPolicy(), e, log);
}
}
return null;
}
Aggregations