Project

General

Profile

1
package eu.dnetlib.data.search.transform.formatter;
2

    
3
import eu.dnetlib.data.search.transform.FormatterException;
4
import eu.dnetlib.domain.data.SearchResult;
5
import org.apache.log4j.Logger;
6

    
7
import javax.xml.transform.TransformerFactory;
8
import javax.xml.transform.stream.StreamResult;
9
import javax.xml.transform.stream.StreamSource;
10
import java.io.StringReader;
11
import java.io.StringWriter;
12

    
13
public class XSLTFormatter extends SimpleFormatter implements Formatter {
14

    
15
    private final String xslt;
16

    
17
    private final Logger logger = Logger.getLogger(XSLTFormatter.class);
18

    
19
    private javax.xml.transform.Transformer xmlTransformer = null;
20

    
21
    public XSLTFormatter(String xslt) throws FormatterException {
22
        super();
23
        this.xslt = xslt;
24
        try {
25
            synchronized(this){
26
                xmlTransformer = TransformerFactory.newInstance().newTemplates(new StreamSource(new StringReader(xslt))).newTransformer();
27
                xmlTransformer.setOutputProperty("encoding", "UTF-8");
28
            }
29
        } catch (Exception e) {
30
            logger.warn("Error creating "  + xslt + " transformer.", e);
31
        }
32
    }
33

    
34
    public XSLTFormatter(String xslt, String template) throws FormatterException {
35
        super(template);
36
        this.xslt = xslt;
37
        try {
38
            synchronized(this){
39
                xmlTransformer = TransformerFactory.newInstance().newTemplates(new StreamSource(new StringReader(xslt))).newTransformer();
40
                xmlTransformer.setOutputProperty("encoding", "UTF-8");
41
            }
42
        } catch (Exception e) {
43
            logger.warn("Error creating "  + xslt + " transformer.", e);
44
        }
45
    }
46

    
47
    public synchronized String format(SearchResult result)  throws FormatterException {
48
        String input = super.format(result);
49
        StringWriter xmlResultResource = new StringWriter();
50

    
51
        try {
52
			//logger.debug("The xsl to transform with " + xslt);
53
            //logger.debug("before: " + result.getSearchResults());
54
            xmlTransformer.transform(new StreamSource(new StringReader(input)), new StreamResult(xmlResultResource));
55

    
56
        } catch (Exception e) {
57
            logger.warn("Error transforming xml: " + input, e);
58
            throw new FormatterException("Error transforming xml: " + input, e);
59
        }
60

    
61
        //logger.debug("Transformer returns " + xmlResultResource.toString());
62
        return xmlResultResource.toString();
63
    }
64

    
65
    public String getXslt() {
66
        return xslt;
67
    }
68

    
69
}
(5-5/6)