Project

General

Profile

1
package eu.dnetlib.data.mapreduce.hbase.index.config;
2

    
3
import java.io.StringReader;
4
import java.lang.reflect.Type;
5
import java.util.HashMap;
6
import java.util.List;
7

    
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

    
15
import com.google.common.collect.Lists;
16
import com.google.gson.Gson;
17
import com.google.gson.reflect.TypeToken;
18

    
19
public class ContextMapper extends HashMap<String, ContextDef> {
20

    
21
	private static final long serialVersionUID = 2159682308502487305L;
22

    
23
	private static final Log log = LogFactory.getLog(ContextMapper.class);
24

    
25
	private final Type token = new TypeToken<List<ContextDef>>() {}.getType();
26

    
27
	@SuppressWarnings("unchecked")
28
	public void fromJson(final String json) {
29
		super.clear();
30
		if ((json != null) && !json.isEmpty()) {
31
			for (ContextDef def : (List<ContextDef>) new Gson().fromJson(json, token)) {
32
				super.put(def.getId(), def);
33
			}
34
		} else {
35
			log.warn("unable to inizialize, empty source json string");
36
		}
37
	}
38

    
39
	public static ContextMapper fromXml(final String xml) throws DocumentException {
40
		final ContextMapper contextMapper = new ContextMapper();
41

    
42
		Document doc = new SAXReader().read(new StringReader(xml));
43
		for (Object o : doc.selectNodes("//entry")) {
44
			Node node = (Node) o;
45
			String id = node.valueOf("./@id");
46
			String label = node.valueOf("./@label");
47
			String name = node.valueOf("./@name");
48
			String type = node.valueOf("./@type") + "";
49

    
50
			contextMapper.put(id, new ContextDef(id, label, name, type));
51
		}
52
		return contextMapper;
53
	}
54

    
55
	@Override
56
	public String toString() {
57
		return new Gson().toJson(Lists.newArrayList(this.values()));
58
	}
59

    
60
}
(2-2/8)