Project

General

Profile

1
package eu.dnetlib.enabling.is.registry.schema;
2

    
3
import java.io.StringReader;
4

    
5
import javax.xml.XMLConstants;
6
import javax.xml.transform.stream.StreamSource;
7
import javax.xml.validation.Schema;
8
import javax.xml.validation.SchemaFactory;
9
import javax.xml.validation.Validator;
10

    
11
import org.apache.commons.lang3.StringUtils;
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Component;
16
import org.xml.sax.SAXException;
17

    
18
import eu.dnetlib.DnetConstants;
19
import eu.dnetlib.enabling.is.DnetInformationServiceException;
20
import eu.dnetlib.enabling.is.store.ISStore;
21
import eu.dnetlib.enabling.tools.XQueryUtils;
22

    
23
@Component
24
public class ProfileValidator {
25

    
26
	private static final Log log = LogFactory.getLog(ProfileValidator.class);
27

    
28
	@Autowired
29
	private ISStore isStore;
30

    
31
	@Autowired
32
	private XQueryUtils xqueryUtils;
33

    
34
	public boolean isValid(final String type, final String profile) {
35

    
36
		final Schema schema = getSchema(type);
37

    
38
		if (schema == null) { return false; }
39

    
40
		final Validator validator = schema.newValidator();
41

    
42
		try {
43
			// hack to workaround for #1500
44
			validator.validate(new StreamSource(new StringReader(profile)));
45
			return true;
46
		} catch (final Throwable e) {
47
			log.warn("The profile is not valid");
48
			return false;
49
		}
50
	}
51

    
52
	private Schema getSchema(final String resourceType) {
53
		try {
54
			if (StringUtils.isBlank(resourceType)) { throw new DnetInformationServiceException("Invalid resourceType"); }
55

    
56
			final String schemaSource = isStore.getXML(resourceType, xqueryUtils.getRootCollection() + DnetConstants.RESOURCE_TYPES);
57

    
58
			if ((schemaSource == null) || schemaSource.isEmpty()) {
59
				log.warn("cannot find resource type " + resourceType);
60
				return null;
61
			}
62
			return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(new StringReader(schemaSource)));
63
		} catch (final DnetInformationServiceException e) {
64
			log.warn("cannot find resource type " + resourceType, e);
65
			return null;
66
		} catch (final SAXException e) {
67
			log.fatal("cannot parse resource type schema " + resourceType, e);
68
			return null;
69
		}
70
	}
71

    
72
}
    (1-1/1)