Search in sources :

Example 16 with BlockConditionsDTO

use of org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO in project carbon-apimgt by wso2.

the class BlockConditionDBUtil method getBlockConditions.

public static BlockConditionsDTO getBlockConditions() {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    List api = new ArrayList();
    List application = new ArrayList();
    List<IPLevelDTO> ip = new ArrayList();
    List user = new ArrayList();
    List custom = new ArrayList();
    String sqlQuery = "select * from AM_BLOCK_CONDITIONS";
    List subscription = new ArrayList();
    try {
        conn = BlockConditionDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        rs = ps.executeQuery();
        while (rs.next()) {
            String type = rs.getString("TYPE");
            String value = rs.getString("BLOCK_CONDITION");
            String enabled = rs.getString("ENABLED");
            String tenantDomain = rs.getString("DOMAIN");
            int conditionId = rs.getInt("CONDITION_ID");
            if (Boolean.parseBoolean(enabled)) {
                if (APIConstants.BLOCKING_CONDITIONS_API.equals(type)) {
                    api.add(value);
                } else if (APIConstants.BLOCKING_CONDITIONS_APPLICATION.equals(type)) {
                    application.add(value);
                } else if (APIConstants.BLOCKING_CONDITIONS_IP.equals(type) || APIConstants.BLOCK_CONDITION_IP_RANGE.equals(type)) {
                    IPLevelDTO ipLevelDTO = new IPLevelDTO();
                    ipLevelDTO.setTenantDomain(tenantDomain);
                    ipLevelDTO.setId(conditionId);
                    JsonElement iplevelJson = new JsonParser().parse(value);
                    if (iplevelJson instanceof JsonPrimitive) {
                        JsonPrimitive fixedIp = (JsonPrimitive) iplevelJson;
                        ipLevelDTO.setFixedIp(fixedIp.getAsString());
                        ipLevelDTO.setInvert(Boolean.FALSE);
                        ipLevelDTO.setType(APIConstants.BLOCKING_CONDITIONS_IP);
                    } else if (iplevelJson instanceof JsonObject) {
                        JsonObject ipBlockingJson = (JsonObject) iplevelJson;
                        if (ipBlockingJson.has(APIConstants.BLOCK_CONDITION_FIXED_IP)) {
                            ipLevelDTO.setType(APIConstants.BLOCKING_CONDITIONS_IP);
                            ipLevelDTO.setFixedIp(ipBlockingJson.get(APIConstants.BLOCK_CONDITION_FIXED_IP).getAsString());
                        }
                        if (ipBlockingJson.has(APIConstants.BLOCK_CONDITION_START_IP)) {
                            ipLevelDTO.setType(APIConstants.BLOCK_CONDITION_IP_RANGE);
                            ipLevelDTO.setStartingIp(ipBlockingJson.get(APIConstants.BLOCK_CONDITION_START_IP).getAsString());
                        }
                        if (ipBlockingJson.has(APIConstants.BLOCK_CONDITION_ENDING_IP)) {
                            ipLevelDTO.setEndingIp(ipBlockingJson.get(APIConstants.BLOCK_CONDITION_ENDING_IP).getAsString());
                        }
                        if (ipBlockingJson.has(APIConstants.BLOCK_CONDITION_INVERT)) {
                            ipLevelDTO.setInvert(ipBlockingJson.get(APIConstants.BLOCK_CONDITION_INVERT).getAsBoolean());
                        }
                    }
                    ip.add(ipLevelDTO);
                } else if (APIConstants.BLOCKING_CONDITIONS_USER.equals(type)) {
                    user.add(value);
                } else if ("CUSTOM".equals(type)) {
                    custom.add(value);
                } else if (APIConstants.BLOCKING_CONDITIONS_SUBSCRIPTION.equals(type)) {
                    subscription.add(value);
                }
            }
        }
    } catch (SQLException e) {
        log.error("Error while executing SQL", e);
    } finally {
        BlockConditionDBUtil.closeAllConnections(ps, conn, rs);
    }
    BlockConditionDBUtil.blockConditionsDTO = new BlockConditionsDTO();
    blockConditionsDTO.setApi(api);
    blockConditionsDTO.setApplication(application);
    blockConditionsDTO.setIp(ip);
    blockConditionsDTO.setUser(user);
    blockConditionsDTO.setCustom(custom);
    blockConditionsDTO.setSubscription(subscription);
    return blockConditionsDTO;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) PreparedStatement(java.sql.PreparedStatement) BlockConditionsDTO(org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO) JsonElement(com.google.gson.JsonElement) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) IPLevelDTO(org.wso2.carbon.apimgt.internal.service.dto.IPLevelDTO) JsonParser(com.google.gson.JsonParser)

Example 17 with BlockConditionsDTO

use of org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO in project carbon-apimgt by wso2.

the class APIProviderImplTest method testAddBlockCondition.

@Test
public void testAddBlockCondition() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
    blockConditionsDTO.setUUID("12345");
    Mockito.when(apimgtDAO.addBlockConditions(Mockito.any(BlockConditionsDTO.class))).thenReturn(blockConditionsDTO);
    // condition type IP
    assertEquals("12345", apiProvider.addBlockCondition("IP", "testValue"));
    // condition type User
    assertEquals("12345", apiProvider.addBlockCondition("USER", "testValue"));
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 18 with BlockConditionsDTO

use of org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO in project carbon-apimgt by wso2.

the class ApiMgtDAO method getBlockConditions.

public List<BlockConditionsDTO> getBlockConditions(String tenantDomain) throws APIManagementException {
    Connection connection = null;
    PreparedStatement selectPreparedStatement = null;
    ResultSet resultSet = null;
    List<BlockConditionsDTO> blockConditionsDTOList = new ArrayList<BlockConditionsDTO>();
    try {
        String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITIONS_SQL;
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(true);
        selectPreparedStatement = connection.prepareStatement(query);
        selectPreparedStatement.setString(1, tenantDomain);
        resultSet = selectPreparedStatement.executeQuery();
        while (resultSet.next()) {
            BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
            blockConditionsDTO.setEnabled(resultSet.getBoolean("ENABLED"));
            blockConditionsDTO.setConditionType(resultSet.getString("TYPE"));
            blockConditionsDTO.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
            blockConditionsDTO.setConditionId(resultSet.getInt("CONDITION_ID"));
            blockConditionsDTO.setUUID(resultSet.getString("UUID"));
            blockConditionsDTO.setTenantDomain(resultSet.getString("DOMAIN"));
            blockConditionsDTOList.add(blockConditionsDTO);
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback getting Block conditions ", ex);
            }
        }
        handleException("Failed to get Block conditions", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
    }
    return blockConditionsDTOList;
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement)

Example 19 with BlockConditionsDTO

use of org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO 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)

Example 20 with BlockConditionsDTO

use of org.wso2.carbon.apimgt.internal.service.dto.BlockConditionsDTO in project carbon-apimgt by wso2.

the class APIProviderImpl method addBlockCondition.

@Override
public String addBlockCondition(String conditionType, String conditionValue, boolean conditionStatus) throws APIManagementException {
    if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
        conditionValue = MultitenantUtils.getTenantAwareUsername(conditionValue);
        conditionValue = conditionValue + "@" + tenantDomain;
    }
    BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
    blockConditionsDTO.setConditionType(conditionType);
    blockConditionsDTO.setConditionValue(conditionValue);
    blockConditionsDTO.setTenantDomain(tenantDomain);
    blockConditionsDTO.setEnabled(conditionStatus);
    blockConditionsDTO.setUUID(UUID.randomUUID().toString());
    BlockConditionsDTO createdBlockConditionsDto = apiMgtDAO.addBlockConditions(blockConditionsDTO);
    if (createdBlockConditionsDto != null) {
        publishBlockingEvent(createdBlockConditionsDto, "true");
    }
    return createdBlockConditionsDto.getUUID();
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO)

Aggregations

BlockConditionsDTO (org.wso2.carbon.apimgt.api.model.BlockConditionsDTO)24 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 Connection (java.sql.Connection)6 PreparedStatement (java.sql.PreparedStatement)6 ResultSet (java.sql.ResultSet)6 SQLException (java.sql.SQLException)6 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)5 ParseException (org.json.simple.parser.ParseException)4 ArrayList (java.util.ArrayList)3 JSONObject (org.json.simple.JSONObject)2 BlockingConditionDTO (org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BlockingConditionDTO)2 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Date (java.util.Date)1