package org.jetbrains.mps.samples.money.runtime; /*Generated by MPS */ import java.util.Map; import java.util.List; import jetbrains.mps.internal.collections.runtime.MapSequence; import java.util.HashMap; import jetbrains.mps.internal.collections.runtime.ListSequence; import java.util.ArrayList; import java.net.URL; import java.io.InputStream; import jetbrains.mps.util.URLUtil; import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.StringTokenizer; import java.text.ParseException; import java.net.MalformedURLException; import java.io.IOException; public final class StockPriceDownloader { private static StockPriceDownloader instance = new StockPriceDownloader(); public static StockPriceDownloader getInstance() { return instance; } private StockPriceDownloader() { } private Map<String, List<DailyStockPrice>> priceCache = MapSequence.fromMap(new HashMap<String, List<DailyStockPrice>>()); public void clearCache() { MapSequence.fromMap(priceCache).clear(); } public boolean isValidStockSymbol(String symbol) { return getCurrentPrice(symbol) != null; } public Money getCurrentPrice(String symbol) { if ((symbol != null && symbol.length() > 0)) { try { List<DailyStockPrice> prices = MapSequence.fromMap(priceCache).get(symbol); if (prices == null) { prices = ListSequence.fromList(new ArrayList<DailyStockPrice>()); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol); InputStream stream = URLUtil.openStream(url); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; boolean header = true; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); while ((line = reader.readLine()) != null) { if (!(header)) { String[] item = new String[7]; StringTokenizer tokenizer = new StringTokenizer(line, ","); try { for (int i = 0; i < 7; i++) { item[i] = trim_54jj5w_a0a0a0a2a0a7a1a0a0a21(tokenizer.nextToken()); } DailyStockPrice price = new DailyStockPrice(dateFormat.parse(item[0]), item[1], item[2], item[3], item[4], item[5], item[6]); ListSequence.fromList(prices).addElement(price); } catch (ParseException e) { // date parsing error return null; } catch (IndexOutOfBoundsException e) { // line parsing error return null; } } else { header = false; } } MapSequence.fromMap(priceCache).put(symbol, prices); } return new Money(ListSequence.fromList(prices).getElement(0).getAdjustedClose(), "USD"); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } else { return null; } } public static String trim_54jj5w_a0a0a0a2a0a7a1a0a0a21(String str) { return (str == null ? null : str.trim()); } }