use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method editCommentOfAPI.
@Override
public Response editCommentOfAPI(String commentId, String apiId, PatchRequestBodyDTO patchRequestBodyDTO, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
try {
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
Comment comment = apiConsumer.getComment(apiTypeWrapper, commentId, 0, 0);
if (comment != null) {
if (comment.getUser().equals(username)) {
boolean commentEdited = false;
if (patchRequestBodyDTO.getCategory() != null && !(patchRequestBodyDTO.getCategory().equals(comment.getCategory()))) {
comment.setCategory(patchRequestBodyDTO.getCategory());
commentEdited = true;
}
if (patchRequestBodyDTO.getContent() != null && !(patchRequestBodyDTO.getContent().equals(comment.getText()))) {
comment.setText(patchRequestBodyDTO.getContent());
commentEdited = true;
}
if (commentEdited) {
if (apiConsumer.editComment(apiTypeWrapper, commentId, comment)) {
Comment editedComment = apiConsumer.getComment(apiTypeWrapper, commentId, 0, 0);
CommentDTO commentDTO = CommentMappingUtil.fromCommentToDTO(editedComment);
String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS + "/" + commentId;
URI uri = new URI(uriString);
return Response.ok(uri).entity(commentDTO).build();
}
} else {
return Response.ok().build();
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving comment content location for API " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class RecommendationsApiServiceImpl method recommendationsGet.
public Response recommendationsGet(MessageContext messageContext) throws APIManagementException {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
RecommendationEnvironment recommendationEnvironment = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getApiRecommendationEnvironment();
List<JSONObject> recommendedApis = new ArrayList<>();
JSONObject responseObj = new JSONObject();
String apiId = null;
try {
String userName = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
String requestedTenantDomain = apiConsumer.getRequestedTenant();
if (apiConsumer.isRecommendationEnabled(requestedTenantDomain) && !APIConstants.WSO2_ANONYMOUS_USER.equals(userName)) {
int maxRecommendations = recommendationEnvironment.getMaxRecommendations();
String recommendations = apiConsumer.getApiRecommendations(userName, requestedTenantDomain);
if (recommendations != null) {
JSONObject jsonResponse = new JSONObject(recommendations);
JSONArray apiList = jsonResponse.getJSONArray("userRecommendations");
for (int i = 0; i < apiList.length(); i++) {
try {
JSONObject apiObj = apiList.getJSONObject(i);
apiId = apiObj.getString("id");
ApiTypeWrapper apiWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
API api = apiWrapper.getApi();
APIIdentifier apiIdentifier = api.getId();
boolean isApiSubscribed = apiConsumer.isSubscribed(apiIdentifier, userName);
if (!isApiSubscribed && recommendedApis.size() < maxRecommendations) {
JSONObject apiDetails = new JSONObject();
apiDetails.put("id", apiId);
apiDetails.put("name", apiWrapper.getName());
apiDetails.put("avgRating", api.getRating());
recommendedApis.add(apiDetails);
}
} catch (APIManagementException e) {
log.debug("Requested API " + apiId + " is not accessible by the consumer");
}
}
}
}
} catch (Exception e) {
log.error("Error occurred when retrieving recommendations through the rest api: ", e);
}
int count = recommendedApis.size();
responseObj.put("count", count);
responseObj.put("list", recommendedApis);
String responseStringObj = String.valueOf(responseObj);
return Response.ok().entity(responseStringObj).build();
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper 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.model.ApiTypeWrapper in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method getAdditionalInfoOfAPISubscriptions.
/**
* Get additional Info details of subscriptions attached with given API
*
* @param apiId apiId
* @param offset starting index of the subscription list
* @param limit max num of subscriptions returned
* @param ifNoneMatch If-None-Match header value
* @param messageContext message context
* @return Response with additional Info of the GraphQL API
*/
@Override
public Response getAdditionalInfoOfAPISubscriptions(String apiId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
Subscriber subscriber = new Subscriber(username);
Set<SubscribedAPI> subscriptions;
List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
AdditionalSubscriptionInfoListDTO additionalSubscriptionInfoListDTO;
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
if (apiTypeWrapper.isAPIProduct()) {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
} else {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
}
// Sort subscriptions by application name
subscribedAPIList.addAll(subscriptions);
subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
additionalSubscriptionInfoListDTO = AdditionalSubscriptionInfoMappingUtil.fromAdditionalSubscriptionInfoListToDTO(subscribedAPIList, limit, offset, organization);
AdditionalSubscriptionInfoMappingUtil.setPaginationParams(additionalSubscriptionInfoListDTO, apiId, "", limit, offset, subscribedAPIList.size());
return Response.ok().entity(additionalSubscriptionInfoListDTO).build();
} catch (APIManagementException e) {
// to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving additional information details of the API : " + apiId, e, log);
} else {
String msg = "Error while retrieving additional information details of the API " + apiId;
RestApiUtil.handleInternalServerError(msg, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper 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