Search in sources :

Example 51 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class OAS3Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Open API Specification (3.0) definitions
 *
 * @param apiDefinition API Definition
 * @return swagger Json
 */
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
        int minResponseCode = 0;
        int responseCode = 0;
        String path = entry.getKey();
        Map<String, Schema> definitions = swagger.getComponents().getSchemas();
        // operation map to get verb
        Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
        List<Operation> operations = swagger.getPaths().get(path).readOperations();
        for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
            Operation op = operations.get(i);
            // initializing apiResourceMediationPolicyObject
            APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
            // setting path for apiResourceMediationPolicyObject
            apiResourceMediationPolicyObject.setPath(path);
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            // for each HTTP method get the verb
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
                apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
            } else {
                throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
            }
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                Content content = op.getResponses().get(responseEntry).getContent();
                if (content != null) {
                    MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
                    MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        Schema jsonSchema = applicationJson.getSchema();
                        if (jsonSchema != null) {
                            String jsonExample = getJsonExample(jsonSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                            respCodeInitialized = true;
                            hasJsonPayload = true;
                        }
                    }
                    if (applicationXml != null) {
                        Schema xmlSchema = applicationXml.getSchema();
                        if (xmlSchema != null) {
                            String xmlExample = getXmlExample(xmlSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                            hasXmlPayload = true;
                        }
                    }
                } else {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            // inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            // gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            // sets script to each resource in the swagger
            op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
        }
        checkAndSetEmptyScope(swagger);
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediaType(io.swagger.v3.oas.models.media.MediaType) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Content(io.swagger.v3.oas.models.media.Content) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 52 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition 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 53 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class BlockingConditionMappingUtil method fromBlockConditionListToListDTO.

/**
 * Converts a List of Block Condition in to REST API LIST DTO Object
 *
 * @param blockConditionList A List of Block Conditions
 * @return REST API List DTO object derived from Block Condition list
 */
public static BlockingConditionListDTO fromBlockConditionListToListDTO(List<BlockConditionsDTO> blockConditionList) throws ParseException {
    BlockingConditionListDTO listDTO = new BlockingConditionListDTO();
    List<BlockingConditionDTO> blockingConditionDTOList = new ArrayList<>();
    if (blockConditionList != null) {
        for (BlockConditionsDTO blockCondition : blockConditionList) {
            BlockingConditionDTO dto = fromBlockingConditionToDTO(blockCondition);
            blockingConditionDTOList.add(dto);
        }
    }
    listDTO.setCount(blockingConditionDTOList.size());
    listDTO.setList(blockingConditionDTOList);
    return listDTO;
}
Also used : BlockingConditionListDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BlockingConditionListDTO) BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) ArrayList(java.util.ArrayList) BlockingConditionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BlockingConditionDTO)

Example 54 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class ApiMgtDAO method getBlockConditionByUUID.

/**
 * Get details of a block condition by UUID
 *
 * @param uuid uuid of the block condition
 * @return Block condition represented by the UUID
 * @throws APIManagementException
 */
public BlockConditionsDTO getBlockConditionByUUID(String uuid) throws APIManagementException {
    Connection connection = null;
    PreparedStatement selectPreparedStatement = null;
    ResultSet resultSet = null;
    BlockConditionsDTO blockCondition = null;
    try {
        String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_BY_UUID_SQL;
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(true);
        selectPreparedStatement = connection.prepareStatement(query);
        selectPreparedStatement.setString(1, uuid);
        resultSet = selectPreparedStatement.executeQuery();
        if (resultSet.next()) {
            blockCondition = new BlockConditionsDTO();
            blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
            blockCondition.setConditionType(resultSet.getString("TYPE"));
            blockCondition.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
            blockCondition.setConditionId(resultSet.getInt("CONDITION_ID"));
            blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
            blockCondition.setUUID(resultSet.getString("UUID"));
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback getting Block condition by uuid " + uuid, ex);
            }
        }
        handleException("Failed to get Block condition by uuid " + uuid, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
    }
    return blockCondition;
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 55 with Condition

use of org.wso2.carbon.apimgt.api.model.policy.Condition in project carbon-apimgt by wso2.

the class APIProviderImplTest method getPolicyAPILevelPerUser.

private APIPolicy getPolicyAPILevelPerUser() {
    APIPolicy policy = new APIPolicy("custom1");
    policy.setUserLevel(PolicyConstants.PER_USER);
    policy.setDescription("Description");
    // policy.setPolicyLevel("api");
    policy.setTenantDomain("carbon.super");
    RequestCountLimit defaultLimit = new RequestCountLimit();
    defaultLimit.setTimeUnit("min");
    defaultLimit.setUnitTime(5);
    defaultLimit.setRequestCount(400);
    QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
    defaultQuotaPolicy.setLimit(defaultLimit);
    defaultQuotaPolicy.setType("RequestCount");
    policy.setDefaultQuotaPolicy(defaultQuotaPolicy);
    List<Pipeline> pipelines;
    Pipeline p;
    QuotaPolicy quotaPolicy;
    List<Condition> condition;
    RequestCountLimit countlimit;
    Condition cond;
    pipelines = new ArrayList<Pipeline>();
    // /////////pipeline item start//////
    p = new Pipeline();
    quotaPolicy = new QuotaPolicy();
    quotaPolicy.setType("RequestCount");
    countlimit = new RequestCountLimit();
    countlimit.setTimeUnit("min");
    countlimit.setUnitTime(5);
    countlimit.setRequestCount(100);
    quotaPolicy.setLimit(countlimit);
    condition = new ArrayList<Condition>();
    HTTPVerbCondition verbCond = new HTTPVerbCondition();
    verbCond.setHttpVerb("POST");
    condition.add(verbCond);
    p.setQuotaPolicy(quotaPolicy);
    p.setConditions(condition);
    pipelines.add(p);
    // /////////pipeline item end//////
    policy.setPipelines(pipelines);
    return policy;
}
Also used : HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition)

Aggregations

HashMap (java.util.HashMap)39 Test (org.junit.Test)32 Test (org.testng.annotations.Test)31 ArrayList (java.util.ArrayList)30 List (java.util.List)26 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 ConditionDto (org.wso2.carbon.apimgt.impl.dto.ConditionDto)26 MessageContext (org.apache.synapse.MessageContext)25 PreparedStatement (java.sql.PreparedStatement)23 Map (java.util.Map)22 ResultSet (java.sql.ResultSet)20 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)18 Connection (java.sql.Connection)16 SQLException (java.sql.SQLException)16 TreeMap (java.util.TreeMap)16 HeaderCondition (org.wso2.carbon.apimgt.api.model.policy.HeaderCondition)15 JWTClaimsCondition (org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition)15 QueryParameterCondition (org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)15 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)15