Project

General

Profile

1
package eu.dnetlib.miscutils.templates;
2

    
3
import java.io.StringReader;
4
import java.util.LinkedHashMap;
5
import java.util.Map;
6

    
7
import org.antlr.stringtemplate.StringTemplate;
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.dom4j.Document;
11
import org.dom4j.DocumentException;
12
import org.dom4j.Node;
13
import org.dom4j.io.SAXReader;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Component;
16

    
17
import eu.dnetlib.clients.is.InformationServiceClient;
18
import eu.dnetlib.exceptions.DnetGenericException;
19

    
20
@Component
21
public class TemplateUtil {
22

    
23
	@Autowired
24
	private InformationServiceClient isClient;
25

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

    
28
	public Map<String, String> processTemplateProfile(final String profileId, final Map<String, Object> map) throws DnetGenericException {
29

    
30
		final String profile = isClient.getProfile(profileId);
31

    
32
		try {
33
			final Document doc = (new SAXReader()).read(new StringReader(profile));
34

    
35
			final Map<String, String> res = new LinkedHashMap<>();
36

    
37
			for (final Object o : doc.selectNodes("//TEMPLATE")) {
38
				final String type = ((Node) o).valueOf("@type");
39
				final String language = ((Node) o).valueOf("@language");
40
				final String template = ((Node) o).getText();
41

    
42
				switch (language) {
43
				case "StringTemplate":
44
					final StringTemplate st = new StringTemplate(template);
45
					st.setAttributes(map);
46
					res.put(type, st.toString());
47
					break;
48
				default:
49
					log.error("Unknown template language: " + language);
50
					throw new DnetGenericException("Unknown template language: " + language);
51
				}
52
			}
53

    
54
			if (res.isEmpty()) {
55
				log.error("Empty result for template: " + profileId);
56
				throw new DnetGenericException("Empty result for template: " + profileId);
57
			}
58

    
59
			return res;
60
		} catch (final DocumentException e) {
61
			log.error("Error processing template: " + profileId, e);
62
			throw new DnetGenericException("Error processing template: " + profileId, e);
63
		}
64

    
65
	}
66

    
67
}
    (1-1/1)