Project

General

Profile

1
package eu.dnetlib.utils.ontologies;
2

    
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
6
import java.util.Map;
7

    
8
import com.google.common.collect.Maps;
9
import com.google.gson.GsonBuilder;
10

    
11
import eu.dnetlib.data.mapreduce.util.RelDescriptor;
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14

    
15
/**
16
 * Created by sandro on 12/13/16.
17
 */
18
public class Ontologies extends HashMap<String, Ontology> {
19

    
20
    private static final Log log = LogFactory.getLog(Ontologies.class);
21

    
22
    private Map<String, List<OntologyTerm>> inverse = Maps.newHashMap();
23

    
24
    public String inverseOf(final RelDescriptor rd) {
25

    
26
        if (!containsKey(rd.getRelType())) {
27
            log.warn(String.format("unable to find ontology '%s'", rd.getRelType()));
28
            return null;
29
        }
30
        return get(rd.getRelType()).inverseOf(rd.getRelClass());
31
    }
32

    
33
    public List<OntologyTerm> getTerms(final String termCode) {
34
        if (inverse.isEmpty()) {
35
            initInverse();
36
        }
37
        return inverse.get(termCode);
38
    }
39

    
40
    private void initInverse() {
41
        log.info("initialising inverse Ontology terms");
42
        values().forEach(o -> o.getTerms().values().forEach(t -> {
43
            if (!inverse.containsKey(t.getCode())) {
44
                inverse.put(t.getCode(), new ArrayList<>());
45
            }
46
            inverse.get(t.getCode()).add(t);
47
        }));
48

    
49
    }
50

    
51
    public String toJson() {
52
        return toJson(false);
53
    }
54

    
55
    public String toJson(boolean pretty) {
56

    
57
        final GsonBuilder gson = new GsonBuilder();
58
        if (pretty) {
59
            gson.setPrettyPrinting();
60
        }
61

    
62
        return gson.create().toJson(this);
63
    }
64

    
65
    @Override
66
    public String toString() {
67
        return toJson();
68
    }
69

    
70
}
(1-1/3)