Search in sources :

Example 1 with ParserException

use of org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException in project wso2-synapse by wso2.

the class NumericValidator method validateNumeric.

/**
 * Take JSON schema, number as a string input and validate.
 *
 * @param inputObject JSON schema.
 * @param value       numeric value
 * @return JsonPrimitive contains a number
 * @throws ParserException    Exception occurred in data type conversions.
 * @throws ValidatorException Exception occurred in schema validations.
 */
public static JsonPrimitive validateNumeric(JsonObject inputObject, String value) throws ParserException, ValidatorException {
    Double multipleOf;
    if (value == null) {
        throw new ValidatorException("Expected a number but found null");
    }
    // replacing enclosing quotes
    value = JsonProcessorUtils.replaceEnclosingQuotes(value);
    if (isNumeric(value)) {
        String type = "";
        if (inputObject.has(ValidatorConstants.TYPE_KEY)) {
            if (inputObject.get(ValidatorConstants.TYPE_KEY).isJsonArray()) {
                for (JsonElement typeValue : inputObject.get(ValidatorConstants.TYPE_KEY).getAsJsonArray()) {
                    type += JsonProcessorUtils.replaceEnclosingQuotes(typeValue.getAsString());
                }
            } else {
                type = JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(ValidatorConstants.TYPE_KEY).getAsString());
            }
        }
        // handling multiples of condition
        Double doubleValue = DataTypeConverter.convertToDouble(value);
        if (inputObject.has(MULTIPLE_OF)) {
            multipleOf = DataTypeConverter.convertToDouble(JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(MULTIPLE_OF).getAsString()));
            if (doubleValue % multipleOf != 0) {
                throw new ValidatorException("Number " + value + " is not a multiple of " + "" + multipleOf + ". multipleOf constraint in " + inputObject.toString() + " is violated " + "by the input " + value);
            }
        }
        // handling maximum and minimum
        if (inputObject.has(MINIMUM_VALUE)) {
            String minimumString = JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(MINIMUM_VALUE).getAsString());
            if (!minimumString.isEmpty() && doubleValue < DataTypeConverter.convertToDouble(minimumString)) {
                throw new ValidatorException("Number " + value + " is less than the " + "minimum allowed value" + ". minimumValue constraint in " + inputObject.toString() + " is violated by the input " + ": " + value);
            }
        }
        if (inputObject.has(MAXIMUM_VALUE)) {
            String maximumString = JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(MAXIMUM_VALUE).getAsString());
            if (!maximumString.isEmpty() && doubleValue > DataTypeConverter.convertToDouble(maximumString)) {
                throw new ValidatorException("Number " + value + " is greater than the " + "maximum allowed value. maximumValue constraint in " + inputObject.toString() + " is violated by the input " + ": " + value);
            }
        }
        // handling exclusive maximum and minimum
        if (inputObject.has(EXCLUSIVE_MINIMUM)) {
            String minimumString = JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(EXCLUSIVE_MINIMUM).getAsString());
            if (!minimumString.isEmpty() && doubleValue <= DataTypeConverter.convertToDouble(minimumString)) {
                throw new ValidatorException("Number " + value + " is less than the " + "minimum allowed value. ExclusiveMinimum constraint in " + inputObject.toString() + " is violated by the " + "input : " + value);
            }
        }
        if (inputObject.has(EXCLUSIVE_MAXIMUM)) {
            String maximumString = JsonProcessorUtils.replaceEnclosingQuotes(inputObject.get(EXCLUSIVE_MAXIMUM).getAsString());
            if (!maximumString.isEmpty() && doubleValue >= DataTypeConverter.convertToDouble(maximumString)) {
                throw new ValidatorException("Number " + value + " is greater than the " + "maximum allowed value. ExclusiveMaximum constraint in " + inputObject.toString() + " is violated by the " + "input : " + value);
            }
        }
        // Enum validations
        if (inputObject.has(ValidatorConstants.ENUM)) {
            JsonArray enumElements = inputObject.getAsJsonArray(ValidatorConstants.ENUM);
            if (enumElements.size() > 0 && !enumElements.contains(new JsonPrimitive(doubleValue))) {
                throw new ValidatorException("Number \"" + value + "\" not contains any " + "element from the enum. Input " + value + " not contains any value from the enum in " + inputObject.toString());
            }
        }
        // Const validation
        if (inputObject.has(ValidatorConstants.CONST) && !doubleValue.equals(inputObject.getAsJsonPrimitive(ValidatorConstants.CONST).getAsDouble())) {
            throw new ValidatorException("Number \"" + value + "\" is not equal to the " + "const value input " + value + " not contains the const defined in " + inputObject.toString());
        }
        // convert to integer of give value is a float
        if (type.contains(INTEGER_STRING)) {
            return new JsonPrimitive(DataTypeConverter.convertToInt(value));
        } else {
            // this condition address both type number and empty json schemas
            return new JsonPrimitive(doubleValue);
        }
    }
    throw new ParserException("\"" + value + "\"" + " is not a number. " + "A number expected in the schema " + inputObject.toString() + " but received " + value);
}
Also used : JsonArray(com.google.gson.JsonArray) ParserException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException) ValidatorException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement)

Example 2 with ParserException

use of org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException in project wso2-synapse by wso2.

the class JsonProcessor method parseJson.

/**
 * This method will parse a given JSON string according to the given schema. Schema as an Object.
 * Can use this method when using caching.
 *
 * @param inputString input JSON string.
 * @param schema      already parsed JSON schema.
 * @return corrected JSON string.
 * @throws ValidatorException Exception occurs in validation process.
 * @throws ParserException    Exception occurs in data type parsing.
 */
private static String parseJson(String inputString, Object schema) throws ValidatorException, ParserException {
    if (StringUtils.isNotEmpty(inputString) && schema instanceof JsonObject) {
        JsonElement result = null;
        JsonObject schemaObject = (JsonObject) schema;
        if (((JsonObject) schema).has(ValidatorConstants.TYPE_KEY)) {
            String type = JsonProcessorUtils.replaceEnclosingQuotes(schemaObject.get(ValidatorConstants.TYPE_KEY).toString());
            if (ValidatorConstants.BOOLEAN_KEYS.contains(type)) {
                result = BooleanValidator.validateBoolean(schemaObject, inputString);
            } else if (ValidatorConstants.NOMINAL_KEYS.contains(type)) {
                result = StringValidator.validateNominal(schemaObject, inputString);
            } else if (ValidatorConstants.NUMERIC_KEYS.contains(type)) {
                result = NumericValidator.validateNumeric(schemaObject, inputString);
            } else if (ValidatorConstants.ARRAY_KEYS.contains(type)) {
                result = ArrayValidator.validateArray(GSONDataTypeConverter.getMapFromString(inputString), schemaObject);
            } else if (ValidatorConstants.NULL_KEYS.contains(type)) {
                NullValidator.validateNull(schemaObject, inputString);
                result = JsonNull.INSTANCE;
            } else if (ValidatorConstants.OBJECT_KEYS.contains(type)) {
                JsonElement input = parser.parse(inputString);
                if (input.isJsonObject()) {
                    result = ObjectValidator.validateObject(input.getAsJsonObject(), schemaObject);
                } else {
                    throw new ValidatorException("Expected a JSON as input but found : " + inputString);
                }
            }
            if (result != null) {
                return result.toString();
            }
            return null;
        } else {
            throw new ValidatorException("JSON schema should contain a type declaration");
        }
    } else {
        throw new ParserException("Input json and schema should not be null, " + "schema should be a JSON object");
    }
}
Also used : ParserException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException) ValidatorException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject)

Example 3 with ParserException

use of org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException in project wso2-synapse by wso2.

the class JsonProcessor method parseJson.

/**
 * This method parse a given JSON string according to the given schema. Both as string.
 *
 * @param inputString input String.
 * @param inputSchema input Schema.
 * @return corrected String.
 * @throws ValidatorException Exception occurs in validation process.
 * @throws ParserException    Exception occurs in data type parsing.
 */
public static String parseJson(String inputString, String inputSchema) throws ValidatorException, ParserException {
    if (StringUtils.isNotEmpty(inputString) && StringUtils.isNotEmpty(inputSchema)) {
        JsonObject schemaObject;
        JsonElement schema;
        try {
            schema = parser.parse(inputSchema);
        } catch (JsonSyntaxException ex) {
            throw new ValidatorException("Invalid JSON schema", ex);
        }
        if (schema.isJsonObject()) {
            // Handling empty JSON objects - valid for all inputs
            if (schema.toString().replaceAll("\\s+", "").equals("{}")) {
                return inputString;
            }
            schemaObject = schema.getAsJsonObject();
        } else if (schema.isJsonPrimitive()) {
            // if schema is primitive it should be a boolean
            boolean valid = schema.getAsBoolean();
            if (valid) {
                return inputString;
            } else {
                throw new ValidatorException("JSON schema is false, so all validations will fail");
            }
        } else {
            throw new ValidatorException("JSON schema should be an object or boolean");
        }
        return parseJson(inputString, schemaObject);
    } else {
        throw new ParserException("Input json and schema should not be null");
    }
}
Also used : ParserException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ValidatorException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject)

Example 4 with ParserException

use of org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException in project wso2-synapse by wso2.

the class JSONTransformMediator method mediate.

@Override
public boolean mediate(MessageContext synCtx) {
    if (synCtx.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(synCtx)) {
            return true;
        }
    }
    SynapseLog synLog = getLog(synCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Start : JSONTransform mediator");
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Message : " + synCtx.getEnvelope());
        }
    }
    if (!propertiesArrayList.isEmpty()) {
        try {
            // Passing the the custom jsonOutputFactory and converting the Envelope body to JSON
            String jsonPayloadFromOMElement = JsonUtil.toJsonString(((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().getBody().getFirstElement(), jsonOutputFactory).toString();
            // Update the jsonstream with the newly build payload
            JsonUtil.getNewJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext(), jsonPayloadFromOMElement, true, true);
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("JSON stream after converting xml to json : " + jsonPayloadFromOMElement);
            }
        } catch (AxisFault af) {
            handleException("Axisfault occured when updating the " + "JSON stream after applying the properties: ", af, synCtx);
        }
    }
    if (schemaKey != null) {
        // Derive actual key from message context
        String generatedSchemaKey = schemaKey.evaluateValue(synCtx);
        Object jsonSchemaObj = synCtx.getEntry(generatedSchemaKey);
        if (jsonSchemaObj != null) {
            String schema = "";
            if (jsonSchemaObj instanceof OMTextImpl) {
                try {
                    // reading the schema with the media-type application/json
                    schema = JsonLoader.fromReader(new InputStreamReader(((OMTextImpl) jsonSchemaObj).getInputStream())).toString();
                } catch (OMException e) {
                    // reading the schema with the media type "unknown"
                    schema = ((OMTextImpl) jsonSchemaObj).getText();
                } catch (IOException e) {
                    handleException("Error while reading schema from registry", e, synCtx);
                }
            } else if (jsonSchemaObj instanceof String) {
                schema = (String) jsonSchemaObj;
            } else {
                handleException("Can not find valid JSON Schema content", synCtx);
            }
            try {
                String jsonPayload;
                if (JsonUtil.hasAJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext())) {
                    jsonPayload = JsonUtil.jsonPayloadToString(((Axis2MessageContext) synCtx).getAxis2MessageContext());
                } else {
                    jsonPayload = JsonUtil.toJsonString(((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().getBody().getFirstElement()).toString();
                }
                String result = JsonProcessor.parseJson(jsonPayload, schema);
                JsonUtil.getNewJsonPayload(((Axis2MessageContext) synCtx).getAxis2MessageContext(), result, true, true);
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.traceOrDebug("JSON stream after applying schema : " + ((result != null) ? result : ""));
                }
            } catch (ValidatorException | ParserException e) {
                handleException(e.getMessage(), e, synCtx);
            } catch (AxisFault af) {
                handleException("Axisfault fault occured when updating the " + "JSON stream after applying the JSON schema", af, synCtx);
            }
        } else {
            handleException("Schema does not exist in the specified location : " + generatedSchemaKey, synCtx);
        }
    }
    synLog.traceOrDebug("End : JSON Transform mediator");
    return true;
}
Also used : AxisFault(org.apache.axis2.AxisFault) ParserException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException) SynapseLog(org.apache.synapse.SynapseLog) ValidatorException(org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException) InputStreamReader(java.io.InputStreamReader) OMTextImpl(org.apache.axiom.om.impl.llom.OMTextImpl) IOException(java.io.IOException) OMException(org.apache.axiom.om.OMException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

ParserException (org.apache.synapse.commons.json.jsonprocessor.exceptions.ParserException)4 ValidatorException (org.apache.synapse.commons.json.jsonprocessor.exceptions.ValidatorException)4 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)2 JsonArray (com.google.gson.JsonArray)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OMException (org.apache.axiom.om.OMException)1 OMTextImpl (org.apache.axiom.om.impl.llom.OMTextImpl)1 AxisFault (org.apache.axis2.AxisFault)1 SynapseLog (org.apache.synapse.SynapseLog)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1