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;
}
}
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;
}
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;
}
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;
}
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;
}
Aggregations