Search in sources :

Example 1 with BlockConditionAlreadyExistsException

use of org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException 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)

Example 2 with BlockConditionAlreadyExistsException

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

the class BlacklistApiServiceImpl method blacklistPost.

/**
 * Add a blacklist condition.
 *
 * @param body        DTO object including the blacklist condition data
 * @param request     msf4j request object
 * @return Response object
 * @throws NotFoundException if an error occurred when particular resource does not exits in the system.
 */
@Override
public Response blacklistPost(BlockingConditionDTO body, Request request) throws NotFoundException {
    if (log.isDebugEnabled()) {
        log.debug("Received BlockCondition POST request with body: " + body);
    }
    try {
        APIMgtAdminService apiMgtAdminService = RestApiUtil.getAPIMgtAdminService();
        // Add the block condition. It will throw BlockConditionAlreadyExistsException if the condition already
        // exists in the system
        BlockConditions blockConditions = BlockingConditionMappingUtil.fromBlockingConditionDTOToBlockCondition(body);
        String uuid = apiMgtAdminService.addBlockCondition(blockConditions);
        // retrieve the new blocking condition and send back as the response
        BlockConditions newBlockingCondition = apiMgtAdminService.getBlockConditionByUUID(uuid);
        BlockingConditionDTO dto = BlockingConditionMappingUtil.fromBlockingConditionToDTO(newBlockingCondition);
        return Response.status(Response.Status.CREATED).entity(dto).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error occurred while adding blocking condition with UUID " + body.getConditionId();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) BlockConditions(org.wso2.carbon.apimgt.core.models.BlockConditions) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)

Example 3 with BlockConditionAlreadyExistsException

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

the class ApiMgtDAO method addBlockConditions.

/**
 * Add a block condition
 *
 * @return uuid of the block condition if successfully added
 * @throws APIManagementException
 */
public BlockConditionsDTO addBlockConditions(BlockConditionsDTO blockConditionsDTO) throws APIManagementException {
    Connection connection = null;
    PreparedStatement insertPreparedStatement = null;
    boolean status = false;
    boolean valid = false;
    ResultSet rs = null;
    String uuid = blockConditionsDTO.getUUID();
    String conditionType = blockConditionsDTO.getConditionType();
    String conditionValue = blockConditionsDTO.getConditionValue();
    String tenantDomain = blockConditionsDTO.getTenantDomain();
    String conditionStatus = String.valueOf(blockConditionsDTO.isEnabled());
    try {
        String query = SQLConstants.ThrottleSQLConstants.ADD_BLOCK_CONDITIONS_SQL;
        if (APIConstants.BLOCKING_CONDITIONS_API.equals(conditionType)) {
            String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(conditionValue);
            if (extractedTenantDomain == null) {
                extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            }
            if (tenantDomain.equals(extractedTenantDomain) && isValidContext(conditionValue)) {
                valid = true;
            } else {
                throw new APIManagementException("Couldn't Save Block Condition Due to Invalid API Context " + conditionValue);
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_APPLICATION.equals(conditionType)) {
            String[] appArray = conditionValue.split(":");
            if (appArray.length > 1) {
                String appOwner = appArray[0];
                String appName = appArray[1];
                if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
                }
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
            if (MultitenantUtils.getTenantDomain(conditionValue).equals(tenantDomain)) {
                valid = true;
            } else {
                throw new APIManagementException("Invalid User in Tenant Domain " + tenantDomain);
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_IP.equals(conditionType) || APIConstants.BLOCK_CONDITION_IP_RANGE.equals(conditionType)) {
            valid = true;
        } else if (APIConstants.BLOCKING_CONDITIONS_SUBSCRIPTION.equals(conditionType)) {
            /* ATM this condition type will be used internally to handle subscription blockings for JWT type access
                   tokens.
                */
            String[] conditionsArray = conditionValue.split(":");
            if (conditionsArray.length > 0) {
                String apiContext = conditionsArray[0];
                String applicationIdentifier = conditionsArray[2];
                String[] app = applicationIdentifier.split("-", 2);
                String appOwner = app[0];
                String appName = app[1];
                // Check whether the given api context exists in tenant
                String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(apiContext);
                if (extractedTenantDomain == null) {
                    extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
                }
                if (tenantDomain.equals(extractedTenantDomain) && isValidContext(apiContext)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid API Context " + apiContext);
                }
                // Check whether the given application is valid
                if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
                }
            } else {
                throw new APIManagementException("Invalid subscription block condition with insufficient data : " + conditionValue);
            }
        }
        if (valid) {
            connection = APIMgtDBUtil.getConnection();
            connection.setAutoCommit(false);
            if (!isBlockConditionExist(conditionType, conditionValue, tenantDomain, connection)) {
                String dbProductName = connection.getMetaData().getDatabaseProductName();
                insertPreparedStatement = connection.prepareStatement(query, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "CONDITION_ID") });
                insertPreparedStatement.setString(1, conditionType);
                insertPreparedStatement.setString(2, conditionValue);
                insertPreparedStatement.setString(3, conditionStatus);
                insertPreparedStatement.setString(4, tenantDomain);
                insertPreparedStatement.setString(5, uuid);
                insertPreparedStatement.execute();
                ResultSet generatedKeys = insertPreparedStatement.getGeneratedKeys();
                if (generatedKeys != null && generatedKeys.next()) {
                    blockConditionsDTO.setConditionId(generatedKeys.getInt(1));
                }
                connection.commit();
                status = true;
            } else {
                throw new BlockConditionAlreadyExistsException("Condition with type: " + conditionType + ", value: " + conditionValue + " already exists");
            }
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback adding Block condition : " + conditionType + " and " + conditionValue, ex);
            }
        }
        handleException("Failed to add Block condition : " + conditionType + " and " + conditionValue, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(insertPreparedStatement, connection, null);
    }
    if (status) {
        return blockConditionsDTO;
    } else {
        return null;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) BlockConditionAlreadyExistsException(org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Map (java.util.Map)1 JSONObject (org.json.simple.JSONObject)1 ParseException (org.json.simple.parser.ParseException)1 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)1 BlockConditionAlreadyExistsException (org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException)1 BlockConditionsDTO (org.wso2.carbon.apimgt.api.model.BlockConditionsDTO)1 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)1 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)1 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)1 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)1