Search in sources :

Example 91 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class APIDefinitionFromOpenAPISpec method validateScopesFromSwagger.

/**
 * Called using the jaggery api. Checks if the swagger contains valid api scopes.
 *
 * @param swagger Swagger definition
 * @return true if the scope definition is valid
 * @throws APIManagementException
 */
public Boolean validateScopesFromSwagger(String swagger) throws APIManagementException {
    try {
        Set<Scope> scopes = getScopes(swagger);
        JSONParser parser = new JSONParser();
        JSONObject swaggerJson;
        swaggerJson = (JSONObject) parser.parse(swagger);
        if (swaggerJson.get("paths") != null) {
            JSONObject paths = (JSONObject) swaggerJson.get("paths");
            for (Object uriTempKey : paths.keySet()) {
                String uriTemp = (String) uriTempKey;
                // if url template is a custom attribute "^x-" ignore.
                if (uriTemp.startsWith("x-") || uriTemp.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTemp);
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    continue;
                }
                for (Object httpVerbKey : path.keySet()) {
                    String httpVerb = (String) httpVerbKey;
                    JSONObject operation = (JSONObject) path.get(httpVerb);
                    String operationScope = (String) operation.get(APIConstants.SWAGGER_X_SCOPE);
                    Scope scope = APIUtil.findScopeByKey(scopes, operationScope);
                    if (scope == null && operationScope != null) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (APIManagementException e) {
        handleException("Error when validating scopes", e);
        return false;
    } catch (ParseException e) {
        handleException("Error when validating scopes", e);
        return false;
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 92 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class AsyncApiParser method validateAPIDefinition.

@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    // import and load AsyncAPI HyperSchema for JSON schema validation
    JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
    String protocol = StringUtils.EMPTY;
    boolean validationSuccess = false;
    List<String> validationErrorMessages = null;
    boolean isWebSocket = false;
    JSONObject schemaToBeValidated = new JSONObject(apiDefinition);
    // validate AsyncAPI using JSON schema validation
    try {
        JSONParser parser = new JSONParser();
        org.json.simple.JSONObject json = (org.json.simple.JSONObject) parser.parse(metaSchema);
        SchemaLoader schemaLoader = SchemaLoader.builder().registerSchemaByURI(new URI("http://json-schema.org/draft-07/schema#"), json).schemaJson(hyperSchema).build();
        Schema schemaValidator = schemaLoader.load().build();
        schemaValidator.validate(schemaToBeValidated);
        /*AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
            validationErrorMessages = new ArrayList<>();
            if (asyncApiDocument.getServers().size() == 1) {
                if (!APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
                    validationErrorMessages.add("#:The protocol of the server should be 'ws' for websockets");
                }
            }
            if (asyncApiDocument.getServers().size() > 1) {
                validationErrorMessages.add("#:The AsyncAPI definition should contain only a single server for websockets");
            }
            if (asyncApiDocument.getChannels().size() > 1) {
                validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
            }
            if (validationErrorMessages.size() == 0) {
                validationSuccess = true;
                validationErrorMessages = null;
            }*/
        // AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
        /*//Checking whether it is a websocket
            validationErrorMessages = new ArrayList<>();
            if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
                if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(protocol)) {
                    isWebSocket = true;
                }
            }*/
        // validating channel count for websockets
        /*if (isWebSocket) {
                if (asyncApiDocument.getChannels().size() > 1) {
                    validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
                }
            }*/
        /*if (validationErrorMessages.size() == 0) {
                validationSuccess = true;
                validationErrorMessages = null;
            }*/
        validationSuccess = true;
    } catch (ValidationException e) {
        // validation error messages
        validationErrorMessages = e.getAllMessages();
    } catch (URISyntaxException e) {
        String msg = "Error occurred when registering the schema";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Error occurred when parsing the schema";
        throw new APIManagementException(msg, e);
    }
    // TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
    validationSuccess = true;
    if (validationSuccess) {
        AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
        ArrayList<String> endpoints = new ArrayList<>();
        if (asyncApiDocument.getServers().size() == 1) {
            protocol = asyncApiDocument.getServers().get(0).protocol;
        }
        /*for (AaiServer x : asyncApiDocument.getServers()){
                endpoints.add(x.url);
            }
            AsyncApiParserUtil.updateValidationResponseAsSuccess(
                    validationResponse,
                    apiDefinition,
                    asyncApiDocument.asyncapi,
                    asyncApiDocument.info.title,
                    asyncApiDocument.info.version,
                    null,                           //asyncApiDocument.getChannels().get(0)._name,
                    asyncApiDocument.info.description,
                    endpoints
            );*/
        /*if (isWebSocket) {
                for (AaiServer x : asyncApiDocument.getServers()){
                    endpoints.add(x.url);
                }
                AsyncApiParserUtil.updateValidationResponseAsSuccess(
                        validationResponse,
                        apiDefinition,
                        asyncApiDocument.asyncapi,
                        asyncApiDocument.info.title,
                        asyncApiDocument.info.version,
                        asyncApiDocument.getChannels().get(0)._name,            //make this null
                        asyncApiDocument.info.description,
                        endpoints
                );
            } else {
                AsyncApiParserUtil.updateValidationResponseAsSuccess(
                        validationResponse,
                        apiDefinition,
                        asyncApiDocument.asyncapi,
                        asyncApiDocument.info.title,
                        asyncApiDocument.info.version,
                        null,
                        asyncApiDocument.info.description,
                        null
                );
            }*/
        AsyncApiParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, asyncApiDocument.asyncapi, asyncApiDocument.info.title, asyncApiDocument.info.version, null, asyncApiDocument.info.description, null);
        validationResponse.setParser(this);
        if (returnJsonContent) {
            validationResponse.setJsonContent(apiDefinition);
        }
        if (StringUtils.isNotEmpty(protocol)) {
            validationResponse.setProtocol(protocol);
        }
    } else {
        if (validationErrorMessages != null) {
            validationResponse.setValid(false);
            for (String errorMessage : validationErrorMessages) {
                AsyncApiParserUtil.addErrorToValidationResponse(validationResponse, errorMessage);
            }
        }
    }
    return validationResponse;
}
Also used : SchemaLoader(org.everit.json.schema.loader.SchemaLoader) ValidationException(org.everit.json.schema.ValidationException) Schema(org.everit.json.schema.Schema) ArrayList(java.util.ArrayList) AaiDocument(io.apicurio.datamodels.asyncapi.models.AaiDocument) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 93 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPolicyIdGet.

/**
 * Get a specific Subscription Policy by its uuid
 *
 * @param policyId        uuid of the policy
 * @return Matched Subscription Throttle Policy by the given name
 */
@Override
public Response throttlingPoliciesSubscriptionPolicyIdGet(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 subscriptionPolicy = apiProvider.getSubscriptionPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, subscriptionPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, log);
        }
        SubscriptionThrottlePolicyDTO policyDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyToDTO(subscriptionPolicy);
        // 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 retrieving 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) ParseException(org.json.simple.parser.ParseException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 94 with ParseException

use of org.json.simple.parser.ParseException 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 95 with ParseException

use of org.json.simple.parser.ParseException 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

ParseException (org.json.simple.parser.ParseException)259 JSONObject (org.json.simple.JSONObject)193 JSONParser (org.json.simple.parser.JSONParser)186 JSONArray (org.json.simple.JSONArray)84 IOException (java.io.IOException)72 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 HashMap (java.util.HashMap)41 ArrayList (java.util.ArrayList)34 Map (java.util.Map)23 HashSet (java.util.HashSet)18 API (org.wso2.carbon.apimgt.api.model.API)18 BufferedReader (java.io.BufferedReader)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 List (java.util.List)12 File (java.io.File)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)11 InputStreamReader (java.io.InputStreamReader)10 URL (java.net.URL)10