package fr.insee.eno.params.validation;

import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import fr.insee.eno.Constants;

public class SchemaValidatorImpl implements SchemaValidator {
	
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SchemaValidatorImpl.class);
	
	private Schema schema;
	private Validator validator;
	
	@PostConstruct
	public void initSchemaValidator() {
		SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		try {
			schema = sf.newSchema(Constants.ENO_PARAMETERS_XSD);
		} catch (SAXException e) {
			e.printStackTrace();
		}
		validator = schema.newValidator();
	}
	
	@Override
	public ValidationMessage validate(InputStream paramsIS)  {
		boolean valid=false;
		String message="";
		try {
			validateIS(paramsIS);
			valid=true;
		} catch (Exception e) {
			message = e.getMessage();
			LOGGER.error(message);
		}
		finally {
			LOGGER.info("Validation :"+valid);
		}
		message = valid ? "Parameters respect schema." : message;
		return new ValidationMessage(message, valid);
	}

	public void validateIS(InputStream paramsIS) throws Exception {
		validator.reset();		
		Source source = new StreamSource(paramsIS);
		source = toDOMSource(source);
		validator.validate(source);
	}

	public DOMSource toDOMSource(Source source) throws Exception {
		if (source instanceof DOMSource) {
			return (DOMSource) source;
		}
		Transformer trans = TransformerFactory.newInstance().newTransformer();
		DOMResult result = new DOMResult();
		trans.transform(source, result);
		return new DOMSource(result.getNode());
	}

}

@@ -67,47 +67,8 @@
 m;%0A%0A
-import javax.annotation.PostConstruct;%0A
 impo
@@ -809,40 +809,15 @@
 %0A%09%0A%09
-@PostConstruct%0A%09public void init
+public 
 Sche
@@ -827,16 +827,20 @@
 alidator
+Impl
 () %7B%0A%09%09S
@@ -1078,20 +1078,24 @@
 ator();%0A
+%09%09%0A
 %09%7D%0A%09
+%09
 %0A%09@Overr
@@ -1158,16 +1158,67 @@
 sIS)  %7B%0A
+%09%09LOGGER.info(%22Validation of parameters file...%22);%0A
 %09%09boolea
@@ -1327,16 +1327,40 @@
 on e) %7B%0A
+%09%09%09e.printStackTrace();%0A
 %09%09%09messa
@@ -1661,18 +1661,16 @@
 reset();
-%09%09
 %0A%09%09Sourc

Update SchemaValidatorImpl.java