Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package rjt;
 
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
/* Полная таблица ежедневных курсов Банка России.
 * Источник — официальная выгрузка той же страницы:
 * https://www.cbr.ru/currency_base/daily/
 * JDBC: только executeUpdate со литералами. commit и rollback из Java не вызывать. */
public class CbrChart {
    static final String SOURCE = "https://www.cbr.ru/scripts/XML_daily.asp";
    static final String SITE = "https://www.cbr.ru/currency_base/daily/";
 
    static String page = "";
    static String summary = "";
 
    public static String load() throws Exception {
        String xml = httpGet(SOURCE);
        String date = attr(xml, "Date");
        ArrayList<Rate> rates = ratesOf(xml);
        Collections.sort(rates, new Comparator<Rate>() {
            public int compare(Rate left, Rate right) {
                return Collator.getInstance(new Locale("ru")).compare(left.name, right.name);
            }
        });
        if (rates.size() == 0)
            throw new IllegalStateException("в ответе ЦБ нет валют");
        Statement st = DriverManager.getConnection("jdbc:default:connection:").createStatement();
        st.executeUpdate("delete from rjt_rate");
        for (int i = 0; i < rates.size(); i++)
            st.executeUpdate(insertSql(i + 1, rates.get(i)));
        summary = "ЦБ " + date + ", валют " + rates.size();
        page = pageOf(date, rates);
        return summary;
    }
 
    public static String page() {
        if (page == null || page.length() == 0)
            return "<!DOCTYPE html><meta charset='utf-8'><p>Сначала вызовите rjt_cbr_load().</p>";
        return page;
    }
 
    static String httpGet(String url) throws Exception {
        HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
        /* Корневой УЦ сайта ЦБ нет в cacerts JDK 11. Доверие только у этого запроса, не у всей JVM. */
        if (http instanceof HttpsURLConnection) {
            HttpsURLConnection https = (HttpsURLConnection) http;
            https.setSSLSocketFactory(cbrSsl().getSocketFactory());
            https.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String host, javax.net.ssl.SSLSession session) {
                    return "www.cbr.ru".equals(host);
                }
            });
        }
        http.setConnectTimeout(8000);
        http.setReadTimeout(20000);
        http.setRequestProperty("Accept", "application/xml,text/xml");
        http.setRequestProperty("User-Agent", "rudb-dbms-java-demo");
        int code = http.getResponseCode();
        InputStream in = code >= 400 ? http.getErrorStream() : http.getInputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] chunk = new byte[4096];
        int n;
        while (in != null && (n = in.read(chunk)) >= 0)
            buf.write(chunk, 0, n);
        if (in != null)
            in.close();
        http.disconnect();
        if (code != 200)
            throw new IllegalStateException("HTTP " + code);
        byte[] raw = buf.toByteArray();
        return new String(raw, xmlCharset(raw));
    }
 
    /* Выгрузка ЦБ объявляет windows-1251. Без этого названия валют распадаются. */
    static String xmlCharset(byte[] raw) {
        int n = raw.length < 240 ? raw.length : 240;
        String head = new String(raw, 0, n, java.nio.charset.StandardCharsets.ISO_8859_1);
        String needle = "encoding=\"";
        int at = head.toLowerCase(Locale.US).indexOf(needle);
        if (at < 0)
            return "windows-1251";
        int from = at + needle.length();
        int to = head.indexOf('"', from);
        if (to < 0)
            return "windows-1251";
        return head.substring(from, to);
    }
 
    static SSLContext cbrSsl() throws Exception {
        TrustManager[] trust = new TrustManager[] {
            new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String auth) { }
                public void checkServerTrusted(X509Certificate[] chain, String auth) { }
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trust, new SecureRandom());
        return ctx;
    }
 
    static ArrayList<Rate> ratesOf(String xml) {
        ArrayList<Rate> rates = new ArrayList<Rate>();
        int from = 0;
        while (true) {
            int at = xml.indexOf("<Valute", from);
            if (at < 0)
                break;
            int end = xml.indexOf("</Valute>", at);
            if (end < 0)
                break;
            String block = xml.substring(at, end);
            Rate rate = new Rate();
            rate.numCode = tag(block, "NumCode");
            rate.code = tag(block, "CharCode");
            rate.nominal = Integer.parseInt(tag(block, "Nominal"));
            rate.name = tag(block, "Name");
            rate.value = tag(block, "Value");
            rates.add(rate);
            from = end + 9;
        }
        return rates;
    }
 
    static String tag(String block, String name) {
        String open = "<" + name + ">";
        String close = "</" + name + ">";
        int at = block.indexOf(open);
        int to = block.indexOf(close);
        if (at < 0 || to < 0)
            throw new IllegalStateException("нет " + name);
        return block.substring(at + open.length(), to).trim();
    }
 
    static String attr(String xml, String name) {
        String needle = name + "=\"";
        int at = xml.indexOf(needle);
        if (at < 0)
            return "";
        int from = at + needle.length();
        int to = xml.indexOf('"', from);
        return to < 0 ? "" : xml.substring(from, to);
    }
 
    static String insertSql(int ord, Rate rate) {
        return "insert into rjt_rate(ord, num_code, code, nominal, name, value_txt) values ("
                + ord + ", '" + sqlText(rate.numCode) + "', '" + sqlText(rate.code) + "', "
                + rate.nominal + ", '" + sqlText(rate.name) + "', '" + sqlText(rate.value) + "')";
    }
 
    static String sqlText(String value) {
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            if (c == '\'')
                out.append("''");
            else if (c == '\\' || c == ';' || c < ' ')
                continue;
            else
                out.append(c);
        }
        return out.toString();
    }
 
    static String pageOf(String date, ArrayList<Rate> rates) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html><html lang='ru'><head><meta charset='utf-8'>");
        html.append("<title>Курсы валют на ").append(htmlText(date)).append("</title><style>");
        html.append("body{margin:0;background:#f4f7fb;color:#1b2838;font-family:Arial,sans-serif;}");
        html.append("main{max-width:980px;margin:24px auto 48px;padding:0 16px;}");
        html.append(".kicker{letter-spacing:.12em;text-transform:uppercase;color:#1a5f9e;font-size:12px;}");
        html.append("h1{margin:8px 0 0;font-size:28px;font-weight:650;}");
        html.append(".sub{color:#4d6073;margin:8px 0 18px;line-height:1.45;}");
        html.append("table{width:100%;border-collapse:collapse;background:#fff;box-shadow:0 1px 4px rgba(16,40,64,.08);}");
        html.append("th{background:#1a5f9e;color:#fff;font-weight:600;text-align:left;padding:10px 12px;}");
        html.append("td{padding:8px 12px;border-bottom:1px solid #e4ebf2;}");
        html.append("tr:nth-child(even) td{background:#f7fafc;}");
        html.append(".num{text-align:right;font-variant-numeric:tabular-nums;}");
        html.append(".code{font-weight:700;letter-spacing:.04em;}");
        html.append("a{color:#1a5f9e;}");
        html.append("</style></head><body><main>");
        html.append("<p class='kicker'>rudb · DBMS_JAVA</p>");
        html.append("<h1>Официальные курсы валют</h1>");
        html.append("<p class='sub'>Центральный банк Российской Федерации установил с ");
        html.append(htmlText(date));
        html.append(" следующие курсы иностранных валют к рублю. ");
        html.append("Строки записала Java вызовом из SQL, источник — та же выгрузка, что у ");
        html.append("<a href='").append(SITE).append("'>cbr.ru</a>. Валют: ");
        html.append(rates.size()).append(".</p>");
        html.append("<table><thead><tr>");
        html.append("<th>Цифр. код</th><th>Букв. код</th><th class='num'>Единиц</th>");
        html.append("<th>Валюта</th><th class='num'>Курс</th>");
        html.append("</tr></thead><tbody>");
        for (int i = 0; i < rates.size(); i++) {
            Rate rate = rates.get(i);
            html.append("<tr><td>").append(htmlText(rate.numCode));
            html.append("</td><td class='code'>").append(htmlText(rate.code));
            html.append("</td><td class='num'>").append(rate.nominal);
            html.append("</td><td>").append(htmlText(rate.name));
            html.append("</td><td class='num'>").append(htmlText(rate.value));
            html.append("</td></tr>");
        }
        html.append("</tbody></table></main></body></html>");
        return html.toString();
    }
 
    static String htmlText(String value) {
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            if (c == '&')
                out.append("&amp;");
            else if (c == '<')
                out.append("&lt;");
            else if (c == '>')
                out.append("&gt;");
            else
                out.append(c);
        }
        return out.toString();
    }
 
    static final class Rate {
        String numCode;
        String code;
        String name;
        String value;
        int nominal;
    }
}