Project

General

Profile

1
package eu.dnetlib.goldoa.service;
2

    
3
import eu.dnetlib.goldoa.domain.Currency;
4
import org.springframework.stereotype.Service;
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
 * Created by antleb on 5/4/15.
24
*/
25
@Service("currencyConverter")
26
public class CurrencyConverter {
27

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

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

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

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

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

    
48
	class RateUpdater implements Runnable {
49

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

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

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

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

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

    
70
				rateMap.put(Currency.EUR, 1.0f);
71

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

    
75
					if (rate != null)
76
						rateMap.put(currency, Float.parseFloat(rate));
77
				}
78
			} catch (Exception e) {
79
				e.printStackTrace();
80
			}
81
		}
82
	}
83
}
(9-9/35)