Search in sources :

Example 6 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPolicyIdPut.

/**
 * Updates a given Subscription level policy specified by uuid
 *
 * @param policyId          u
 * @param body              DTO of policy to be updated
 * @param contentType       Content-Type header
 * @return Updated policy
 */
@Override
public Response throttlingPoliciesSubscriptionPolicyIdPut(String policyId, String contentType, SubscriptionThrottlePolicyDTO body, MessageContext messageContext) throws APIManagementException {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // will give PolicyNotFoundException if there's no policy exists with UUID
        SubscriptionPolicy existingPolicy = apiProvider.getSubscriptionPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, existingPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, log);
        }
        // overridden properties
        body.setPolicyId(policyId);
        body.setPolicyName(existingPolicy.getPolicyName());
        // validate if permission info exists and halt the execution in case of an error
        validatePolicyPermissions(body);
        // update the policy
        SubscriptionPolicy subscriptionPolicy = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyDTOToModel(body);
        apiProvider.updatePolicy(subscriptionPolicy);
        // update policy permissions
        updatePolicyPermissions(body);
        // retrieve the new policy and send back as the response
        SubscriptionPolicy newSubscriptionPolicy = apiProvider.getSubscriptionPolicy(username, body.getPolicyName());
        SubscriptionThrottlePolicyDTO policyDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyToDTO(newSubscriptionPolicy);
        // setting policy permissions
        setPolicyPermissionsToDTO(policyDTO);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException | ParseException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while updating Subscription level policy: " + body.getPolicyName();
            throw new APIManagementException(errorMessage, e);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ParseException(org.json.simple.parser.ParseException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 7 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPolicyIdDelete.

/**
 * Delete a Subscription level policy specified by uuid
 *
 * @param policyId          uuid of the policyu
 * @return 200 OK response if successfully deleted the policy
 */
@Override
public Response throttlingPoliciesSubscriptionPolicyIdDelete(String policyId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // This will give PolicyNotFoundException if there's no policy exists with UUID
        SubscriptionPolicy existingPolicy = apiProvider.getSubscriptionPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, existingPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, log);
        }
        if (apiProvider.hasAttachments(username, existingPolicy.getPolicyName(), PolicyConstants.POLICY_LEVEL_SUB)) {
            String message = "Policy " + policyId + " already has subscriptions";
            log.error(message);
            throw new APIManagementException(message);
        }
        apiProvider.deletePolicy(username, PolicyConstants.POLICY_LEVEL_SUB, existingPolicy.getPolicyName());
        return Response.ok().build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while deleting Subscription level policy : " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 8 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesCustomRuleIdPut.

/**
 * Updates a given Global level policy/custom rule specified by uuid
 *
 * @param ruleId            uuid of the policy
 * @param body              DTO of policy to be updated
 * @param contentType       Content-Type header
 * @return Updated policy
 */
@Override
public Response throttlingPoliciesCustomRuleIdPut(String ruleId, String contentType, CustomRuleDTO body, MessageContext messageContext) throws APIManagementException {
    RestApiAdminUtils.validateCustomRuleRequiredProperties(body, (String) messageContext.get(Message.HTTP_REQUEST_METHOD));
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // only super tenant is allowed to access global policies/custom rules
        checkTenantDomainForCustomRules();
        // will give PolicyNotFoundException if there's no policy exists with UUID
        GlobalPolicy existingPolicy = apiProvider.getGlobalPolicyByUUID(ruleId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, existingPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_CUSTOM_RULE, ruleId, log);
        }
        // overridden properties
        body.setPolicyId(ruleId);
        body.setPolicyName(existingPolicy.getPolicyName());
        // update the policy
        GlobalPolicy globalPolicy = GlobalThrottlePolicyMappingUtil.fromGlobalThrottlePolicyDTOToModel(body);
        apiProvider.updatePolicy(globalPolicy);
        // retrieve the new policy and send back as the response
        GlobalPolicy newGlobalPolicy = apiProvider.getGlobalPolicyByUUID(ruleId);
        CustomRuleDTO policyDTO = GlobalThrottlePolicyMappingUtil.fromGlobalThrottlePolicyToDTO(newGlobalPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_CUSTOM_RULE, ruleId, e, log);
        } else {
            String errorMessage = "Error while updating custom rule: " + body.getPolicyName();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 9 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesApplicationPolicyIdPut.

/**
 * Updates a given Application level policy specified by uuid
 *
 * @param policyId          uuid of the policy
 * @param body              DTO of policy to be updated
 * @param contentType       Content-Type header
 * @return Updated policy
 */
@Override
public Response throttlingPoliciesApplicationPolicyIdPut(String policyId, String contentType, ApplicationThrottlePolicyDTO body, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // will give PolicyNotFoundException if there's no policy exists with UUID
        ApplicationPolicy existingPolicy = apiProvider.getApplicationPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, existingPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APP_POLICY, policyId, log);
        }
        // overridden properties
        body.setPolicyId(policyId);
        body.setPolicyName(existingPolicy.getPolicyName());
        // update the policy
        ApplicationPolicy appPolicy = ApplicationThrottlePolicyMappingUtil.fromApplicationThrottlePolicyDTOToModel(body);
        apiProvider.updatePolicy(appPolicy);
        // retrieve the new policy and send back as the response
        ApplicationPolicy newAppPolicy = apiProvider.getApplicationPolicyByUUID(policyId);
        ApplicationThrottlePolicyDTO policyDTO = ApplicationThrottlePolicyMappingUtil.fromApplicationThrottlePolicyToDTO(newAppPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while updating Application level policy: " + body.getPolicyName();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 10 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingDenyPoliciesPost.

/**
 * Add a Block Condition
 *
 * @param body        DTO of new block condition to be created
 * @param contentType Content-Type header
 * @return Created block condition along with the location of it with Location header
 */
@Override
public Response throttlingDenyPoliciesPost(String contentType, BlockingConditionDTO body, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // Add the block condition. It will throw BlockConditionAlreadyExistsException if the condition already
        // exists in the system
        String uuid = null;
        if (ConditionTypeEnum.API.equals(body.getConditionType()) || ConditionTypeEnum.APPLICATION.equals(body.getConditionType()) || ConditionTypeEnum.USER.equals(body.getConditionType())) {
            uuid = apiProvider.addBlockCondition(body.getConditionType().toString(), (String) body.getConditionValue(), body.isConditionStatus());
        } else if (ConditionTypeEnum.IP.equals(body.getConditionType()) || ConditionTypeEnum.IPRANGE.equals(body.getConditionType())) {
            if (body.getConditionValue() instanceof Map) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.putAll((Map) body.getConditionValue());
                if (ConditionTypeEnum.IP.equals(body.getConditionType())) {
                    RestApiAdminUtils.validateIPAddress(jsonObject.get("fixedIp").toString());
                }
                if (ConditionTypeEnum.IPRANGE.equals(body.getConditionType())) {
                    RestApiAdminUtils.validateIPAddress(jsonObject.get("startingIp").toString());
                    RestApiAdminUtils.validateIPAddress(jsonObject.get("endingIp").toString());
                }
                uuid = apiProvider.addBlockCondition(body.getConditionType().toString(), jsonObject.toJSONString(), body.isConditionStatus());
            }
        }
        // retrieve the new blocking condition and send back as the response
        BlockConditionsDTO newBlockingCondition = apiProvider.getBlockConditionByUUID(uuid);
        BlockingConditionDTO dto = BlockingConditionMappingUtil.fromBlockingConditionToDTO(newBlockingCondition);
        return Response.created(new URI(RestApiConstants.RESOURCE_PATH_THROTTLING_BLOCK_CONDITIONS + "/" + uuid)).entity(dto).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceAlreadyExists(e)) {
            RestApiUtil.handleResourceAlreadyExistsError("A black list item with type: " + body.getConditionType() + ", value: " + body.getConditionValue() + " already exists", e, log);
        } else {
            String errorMessage = "Error while adding Blocking Condition. Condition type: " + body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException | ParseException e) {
        String errorMessage = "Error while retrieving Blocking Condition resource location: Condition type: " + body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) ParseException(org.json.simple.parser.ParseException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Map(java.util.Map) URI(java.net.URI)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)207 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)198 API (org.wso2.carbon.apimgt.api.model.API)92 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 Test (org.junit.Test)82 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)82 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)73 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)65 IOException (java.io.IOException)40 ArrayList (java.util.ArrayList)36 URISyntaxException (java.net.URISyntaxException)34 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)32 URI (java.net.URI)31 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)31 JSONObject (org.json.simple.JSONObject)29 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)29 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)29 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)28 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)28 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)23