use of org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException in project carbon-apimgt by wso2.
the class ApiMgtDAO method makeKeysForwardCompatible.
public void makeKeysForwardCompatible(ApiTypeWrapper apiTypeWrapper, List<API> oldAPIVersions) throws APIManagementException {
// if there are no previous versions, there is no need to copy subscriptions
if (oldAPIVersions == null || oldAPIVersions.isEmpty()) {
return;
}
String getSubscriptionDataQuery = SQLConstants.GET_SUBSCRIPTION_DATA_SQL.replaceAll("_API_VERSION_LIST_", String.join(",", Collections.nCopies(oldAPIVersions.size(), "?")));
APIIdentifier apiIdentifier = apiTypeWrapper.getApi().getId();
try {
// Retrieve all the existing subscription for the old version
try (Connection connection = APIMgtDBUtil.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement prepStmt = connection.prepareStatement(getSubscriptionDataQuery)) {
prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
prepStmt.setString(2, apiIdentifier.getApiName());
int index = 3;
for (API oldAPI : oldAPIVersions) {
prepStmt.setString(index++, oldAPI.getId().getVersion());
}
try (ResultSet rs = prepStmt.executeQuery()) {
List<SubscriptionInfo> subscriptionData = new ArrayList<SubscriptionInfo>();
while (rs.next() && !(APIConstants.SubscriptionStatus.ON_HOLD.equals(rs.getString("SUB_STATUS")))) {
int subscriptionId = rs.getInt("SUBSCRIPTION_ID");
String tierId = rs.getString("TIER_ID");
int applicationId = rs.getInt("APPLICATION_ID");
String apiVersion = rs.getString("VERSION");
String subscriptionStatus = rs.getString("SUB_STATUS");
SubscriptionInfo info = new SubscriptionInfo(subscriptionId, tierId, applicationId, apiVersion, subscriptionStatus);
subscriptionData.add(info);
}
// To keep track of already added subscriptions (apps)
List<Integer> addedApplications = new ArrayList<>();
for (int i = oldAPIVersions.size() - 1; i >= 0; i--) {
API oldAPI = oldAPIVersions.get(i);
for (SubscriptionInfo info : subscriptionData) {
try {
if (info.getApiVersion().equals(oldAPI.getId().getVersion()) && !addedApplications.contains(info.getApplicationId())) {
String subscriptionStatus;
if (APIConstants.SubscriptionStatus.BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
subscriptionStatus = APIConstants.SubscriptionStatus.BLOCKED;
} else if (APIConstants.SubscriptionStatus.UNBLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
subscriptionStatus = APIConstants.SubscriptionStatus.UNBLOCKED;
} else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
subscriptionStatus = APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED;
} else if (APIConstants.SubscriptionStatus.REJECTED.equalsIgnoreCase(info.getSubscriptionStatus())) {
subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
} else {
subscriptionStatus = APIConstants.SubscriptionStatus.ON_HOLD;
}
apiTypeWrapper.setTier(info.getTierId());
Application application = getLightweightApplicationById(connection, info.getApplicationId());
int subscriptionId = addSubscription(connection, apiTypeWrapper, application, subscriptionStatus, apiIdentifier.getProviderName());
if (subscriptionId == -1) {
String msg = "Unable to add a new subscription for the API: " + apiIdentifier.getName() + ":v" + apiIdentifier.getVersion();
log.error(msg);
throw new APIManagementException(msg);
}
addedApplications.add(info.getApplicationId());
}
// catching the exception because when copy the api without the option "require
// re-subscription"
// need to go forward rather throwing the exception
} catch (SubscriptionAlreadyExistingException e) {
log.error("Error while adding subscription " + e.getMessage(), e);
} catch (SubscriptionBlockedException e) {
log.info("Subscription is blocked: " + e.getMessage());
}
}
}
}
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
} catch (SQLException e) {
handleException("Error when executing the SQL queries", e);
}
}
use of org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException in project carbon-apimgt by wso2.
the class ApiMgtDAO method addSubscription.
private int addSubscription(Connection connection, ApiTypeWrapper apiTypeWrapper, Application application, String subscriptionStatus, String subscriber) throws APIManagementException, SQLException {
final boolean isProduct = apiTypeWrapper.isAPIProduct();
int subscriptionId = -1;
int id = -1;
String apiUUID;
Identifier identifier;
String tier;
// Query to check if this subscription already exists
String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_API_SQL;
if (!isProduct) {
identifier = apiTypeWrapper.getApi().getId();
apiUUID = apiTypeWrapper.getApi().getUuid();
if (apiUUID != null) {
id = getAPIID(apiUUID);
}
if (id == -1) {
id = identifier.getId();
}
} else {
identifier = apiTypeWrapper.getApiProduct().getId();
id = apiTypeWrapper.getApiProduct().getProductId();
apiUUID = apiTypeWrapper.getApiProduct().getUuid();
}
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
try (PreparedStatement ps = connection.prepareStatement(checkDuplicateQuery)) {
ps.setInt(1, id);
ps.setInt(2, application.getId());
try (ResultSet resultSet = ps.executeQuery()) {
// If the subscription already exists
if (resultSet.next()) {
String subStatus = resultSet.getString("SUB_STATUS");
String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
if ((APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.ON_HOLD.equals(subStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) && APIConstants.SubscriptionCreatedStatus.SUBSCRIBE.equals(subCreationStatus)) {
// Throw error saying subscription already exists.
log.error(String.format("Subscription already exists for API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
throw new SubscriptionAlreadyExistingException(String.format("Subscription already exists for" + " API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
} else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
deleteSubscriptionByApiIDAndAppID(id, application.getId(), connection);
} else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
log.error(String.format(String.format("Subscription to API/API Prouct %%s through application" + " %%s was blocked"), apiTypeWrapper.getName(), application.getName()));
throw new SubscriptionBlockedException(String.format("Subscription to API/API Product %s " + "through application %s was blocked", apiTypeWrapper.getName(), application.getName()));
} else if (APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) {
throw new SubscriptionBlockedException("Subscription to API " + apiTypeWrapper.getName() + " through application " + application.getName() + " was rejected");
}
}
}
}
// This query to update the AM_SUBSCRIPTION table
String sqlQuery = SQLConstants.ADD_SUBSCRIPTION_SQL;
// Adding data to the AM_SUBSCRIPTION table
// ps = conn.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
String subscriptionIDColumn = "SUBSCRIPTION_ID";
String subscriptionUUID = UUID.randomUUID().toString();
if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
subscriptionIDColumn = "subscription_id";
}
try (PreparedStatement preparedStForInsert = connection.prepareStatement(sqlQuery, new String[] { subscriptionIDColumn })) {
if (!isProduct) {
tier = apiTypeWrapper.getApi().getId().getTier();
preparedStForInsert.setString(1, tier);
preparedStForInsert.setString(10, tier);
} else {
tier = apiTypeWrapper.getApiProduct().getId().getTier();
preparedStForInsert.setString(1, tier);
preparedStForInsert.setString(10, tier);
}
preparedStForInsert.setInt(2, id);
preparedStForInsert.setInt(3, application.getId());
preparedStForInsert.setString(4, subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED);
preparedStForInsert.setString(5, APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
preparedStForInsert.setString(6, subscriber);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
preparedStForInsert.setTimestamp(7, timestamp);
preparedStForInsert.setTimestamp(8, timestamp);
preparedStForInsert.setString(9, subscriptionUUID);
preparedStForInsert.executeUpdate();
try (ResultSet rs = preparedStForInsert.getGeneratedKeys()) {
while (rs.next()) {
// subscriptionId = rs.getInt(1);
subscriptionId = Integer.parseInt(rs.getString(1));
}
}
}
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, subscriptionUUID, id, apiUUID, application.getId(), application.getUUID(), tier, (subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED));
return subscriptionId;
}
use of org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException 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.SubscriptionAlreadyExistingException 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;
}
use of org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsMultiplePost.
/**
* Create multiple new subscriptions with the list of subscription details specified in the body parameter.
*
* @param body list of new subscription details
* @return list of newly added subscription as a SubscriptionDTO if successful
*/
@Override
public Response subscriptionsMultiplePost(List<SubscriptionDTO> body, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
List<SubscriptionDTO> subscriptions = new ArrayList<>();
for (SubscriptionDTO subscriptionDTO : body) {
try {
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
String applicationId = subscriptionDTO.getApplicationId();
APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(subscriptionDTO.getApiId(), organization);
// this will throw a APIMgtResourceNotFoundException
if (!org.wso2.carbon.apimgt.rest.api.util.utils.RestAPIStoreUtils.isUserAccessAllowedForAPIByUUID(subscriptionDTO.getApiId(), organization)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, subscriptionDTO.getApiId(), log);
}
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
// required application not found
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
// application access failure occurred
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(subscriptionDTO.getApiId(), organization);
apiTypeWrapper.setTier(subscriptionDTO.getThrottlingPolicy());
SubscriptionResponse subscriptionResponse = apiConsumer.addSubscription(apiTypeWrapper, username, application);
SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, organization);
subscriptions.add(addedSubscriptionDTO);
} 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 " + subscriptionDTO.getApiId() + " for application " + subscriptionDTO.getApplicationId(), e, log);
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
// this happens when the specified API identifier does not exist
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, subscriptionDTO.getApiId(), e, log);
} else {
// unhandled exception
RestApiUtil.handleInternalServerError("Error while adding the subscription API:" + subscriptionDTO.getApiId() + ", application:" + subscriptionDTO.getApplicationId() + ", throttling policy:" + subscriptionDTO.getThrottlingPolicy(), e, log);
}
}
}
return Response.ok().entity(subscriptions).build();
}
Aggregations