All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.formkiq.server.service.ValidatorServiceImpl Maven / Gradle / Ivy

There is a newer version: 0.6.1
Show newest version
package com.formkiq.server.service;

import java.io.IOException;

import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.processors.syntax.SyntaxValidator;

/**
 * Validator Service Implementation.
 *
 */
@Service
public class ValidatorServiceImpl implements ValidatorService {

    /** JSON Syntax Validator. */
	private SyntaxValidator sv = JsonSchemaFactory.byDefault()
			.getSyntaxValidator();

	/**
	 * default contructor.
	 */
	public ValidatorServiceImpl() {
	}

	@Override
	public void validateEmail(final String email) throws InvalidEmailException {

		if (!EmailValidator.getInstance().isValid(email)) {
			throw new InvalidEmailException(email);
		}
	}

	@Override
	public void validateJSON(final String json) throws InvalidJSONException {

		boolean valid;

		try {

			ObjectMapper mapper = new ObjectMapper();
			JsonNode rootNode = mapper.readValue(json, JsonNode.class);
			valid = this.sv.schemaIsValid(rootNode);

		} catch (JsonParseException ex1) {
		    valid = false;
	    } catch (JsonMappingException ex2) {
	        valid = false;
	    } catch (IOException ex) {
	        valid = false;
	    }

		if (!valid) {
		    throw new InvalidJSONException(json);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy