com.formkiq.server.service.ValidatorServiceImpl Maven / Gradle / Ivy
/*
* Copyright (C) 2016 FormKiQ Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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);
}
}
}