Project

General

Profile

1
package eu.dnetlib.data.transform;
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
import eu.dnetlib.data.graph.utils.RelDescriptor;
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13

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

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

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

    
23
	public String inverseOf(final RelDescriptor rd) {
24

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

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

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

    
48
	}
49

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

    
54
	public String toJson(boolean pretty) {
55

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

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

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

    
69
}
(5-5/13)