Project

General

Profile

1
/*
2
package eu.dnetlib.goldoa.service;
3

    
4
import eu.dnetlib.goldoa.domain.Currency;
5
import org.w3c.dom.Document;
6

    
7
import javax.annotation.PostConstruct;
8
import javax.annotation.PreDestroy;
9
import javax.xml.parsers.DocumentBuilder;
10
import javax.xml.parsers.DocumentBuilderFactory;
11
import javax.xml.parsers.ParserConfigurationException;
12
import javax.xml.xpath.XPath;
13
import javax.xml.xpath.XPathExpression;
14
import javax.xml.xpath.XPathExpressionException;
15
import javax.xml.xpath.XPathFactory;
16
import java.util.HashMap;
17
import java.util.Map;
18
import java.util.concurrent.Executors;
19
import java.util.concurrent.ScheduledExecutorService;
20
import java.util.concurrent.TimeUnit;
21

    
22
*/
23
/**
24
 * Created by antleb on 5/4/15.
25
 *//*
26

    
27
public class CurrencyConverter {
28

    
29
	private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
30
	private Map<Currency, Float> rateMap = new HashMap<Currency, Float>();
31

    
32
	@PostConstruct
33
	public void init() throws XPathExpressionException, ParserConfigurationException {
34
		executorService.scheduleAtFixedRate(new RateUpdater(), 0, 1, TimeUnit.HOURS);
35
	}
36

    
37
	@PreDestroy
38
	public void destroy() {
39
		executorService.shutdownNow();
40
	}
41

    
42
	public float convert(Currency from, Currency to, float amount) {
43
		float fromRate = rateMap.get(from);
44
		float toRate = rateMap.get(to);
45

    
46
		return (toRate / fromRate) * amount;
47
	}
48

    
49
	class RateUpdater implements Runnable {
50

    
51
		private Map<Currency, XPathExpression> xpaths = new HashMap<Currency, XPathExpression>();
52
		DocumentBuilder builder;
53

    
54
		public RateUpdater() throws ParserConfigurationException, XPathExpressionException {
55
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
56
			builder = factory.newDocumentBuilder();
57

    
58
			XPathFactory xPathfactory = XPathFactory.newInstance();
59
			XPath xpath = xPathfactory.newXPath();
60

    
61
			for (Currency currency : Currency.values())
62
				if (!currency.equals(Currency.EUR))
63
					xpaths.put(currency, xpath.compile("/*/
64
/*[local-name()='Cube' and @*[local-name()='currency']='" + currency.name() + "']/@rate"));
65
		}
66

    
67
		@Override
68
		public void run() {
69
			try {
70
				Document doc = builder.parse("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
71

    
72
				rateMap.put(Currency.EUR, 1.0f);
73

    
74
				for (Currency currency : xpaths.keySet()) {
75
					String rate = xpaths.get(currency).evaluate(doc);
76

    
77
					if (rate != null)
78
						rateMap.put(currency, Float.parseFloat(rate));
79
				}
80
			} catch (Exception e) {
81
				e.printStackTrace();
82
			}
83
		}
84
	}
85
}
86
*/
(5-5/29)