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("&");
|
else if (c == '<')
|
out.append("<");
|
else if (c == '>')
|
out.append(">");
|
else
|
out.append(c);
|
}
|
return out.toString();
|
}
|
|
static final class Rate {
|
String numCode;
|
String code;
|
String name;
|
String value;
|
int nominal;
|
}
|
}
|