API:Исследователь:Example4

Материал из КардиоКВАРК
Перейти к: навигация, поиск
// REQUIRES: Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files

import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.util.Map.*;
import java.net.URL;
import java.nio.charset.Charset;
import javax.net.ssl.*;
import org.json.*;

public class App {

	private SSLContext nobody;
	private SSLContext researcher;
	private String[] api;
	private String[] cloud;
	
	public App(String apiServer) {
		try {
			api = new String[] { apiServer };
			cloud = new String[0];
			TrustManager[] trustAll = new TrustManager[] {
				new X509TrustManager() {
					public X509Certificate[] getAcceptedIssuers() { return null; }
					public void checkClientTrusted(X509Certificate[] certs, String authType) {}
					public void checkServerTrusted(X509Certificate[] certs, String authType) {}
				}
			};
			nobody = SSLContext.getInstance("TLSv1.2");
			nobody.init(null, trustAll, new SecureRandom());
			researcher = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean Login(String accountId, String password) {
		try {
			if (researcher == null) {
				JSONObject account = new JSONObject();
				account.put("id", Integer.parseInt(accountId));
				account.put("password", password);
				account.put("role", new Integer(3));
				byte[] body = account.toString().getBytes(Charset.forName("UTF-8"));
				byte[] response = request(nobody, "POST", new URL("https", api[0], 1443, "/account?media=P12"), 200, null, "application/json; charset=utf-8", body);
				password = ""; // for P12 file
				KeyStore certs = KeyStore.getInstance("PKCS12");
				certs.load(new ByteArrayInputStream(response), password.toCharArray());
				KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
				kmf.init(certs, password.toCharArray());
				getCa();
				KeyStore cacerts = KeyStore.getInstance(KeyStore.getDefaultType());
				cacerts.load(null, null);
				cacerts.setCertificateEntry("CA", getCa());
				TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
				tmf.init(cacerts);
				researcher = SSLContext.getInstance("TLSv1.2");
				researcher.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
				response = request(researcher, "GET", new URL("https", api[0], 1443, "/settings"), 200, null, null, null);
				JSONObject settings = new JSONObject(new String(response, "UTF-8"));
				JSONArray arr = settings.getJSONArray("api");
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < arr.length(); ++i) list.add(arr.getString(i));
				api = list.toArray(new String[list.size()]);
				arr = settings.getJSONArray("cloud");
				list = new ArrayList<String>();
				for (int i = 0; i < arr.length(); ++i) list.add(arr.getString(i));
				cloud = list.toArray(new String[list.size()]);
			}
			return true;
		} catch (Exception e) {
			researcher = null;
			e.printStackTrace();
			return false;
		}
	}

	public byte[] Read(String path, Map<String, String> header) {
		try {
			return request(researcher, "GET", new URL("https", api[0], 1443, path), 200, header, null, null);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void Download(Long id, Integer type, String token, String fileName) {
		try {
			Map<String, String> header = new HashMap<String, String>();
			header.put("Range", "items=0-9");
			header.put("Authorization", "Token " + token);
			byte[] data = request(nobody, "GET",
				new URL("https", cloud[0], 443, "/cardiogram/"  + Long.toString(id) + "?type=" + Integer.toString(type)),
				200, header, null, null);
			FileOutputStream stream = new FileOutputStream(fileName);
			stream.write(data);
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private X509Certificate getCa() {
		try {
			InputStream inputStream = new ByteArrayInputStream(request(nobody, "GET", new URL("https", api[0], 1443, "/ca?media=DER"), 200, null, null, null));
			return (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private byte[] request(SSLContext context, String method, URL url, int status, Map<String, String> header, String contentType, byte[] body) {
		try {
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(body != null);
			conn.setRequestMethod(method);
			conn.setRequestProperty("Accept", "application/json");
			if (header != null) {
				for (Entry<String, String> entry : header.entrySet()) {
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			conn.setSSLSocketFactory(context.getSocketFactory());
			conn.setUseCaches(false);
			if (body != null) {
				conn.setRequestProperty("Content-Length", Integer.toString(body.length));
				conn.setRequestProperty("Content-Type", contentType);
				OutputStream output = conn.getOutputStream();
				output.write(body);
				output.close();
			}
			int code = conn.getResponseCode();
			if (code != status) throw new Exception("Invalid response code: " + Integer.toString(code));
			InputStream input = conn.getInputStream();
			byte[] buffer = new byte[0x10000]; 
			ByteArrayOutputStream result = new ByteArrayOutputStream(buffer.length);
			int read = 0;
			while (read != -1) {
				read = input.read(buffer);
				if (read > 0) {
					result.write(buffer, 0, read);
				}
			}
			return result.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		try {
			App app = new App("b-api.cardioqvark.ru");
			app.Login("XXX", "XXX");
			Map<String, String> header = new HashMap<String, String>();
			header.put("Range", "items=0-9");
			byte[] data = app.Read("/cardiogram?desc=1&sampleRate=1000", header);
			JSONArray rows = new JSONArray(new String(data, "UTF-8"));
			for (int i = 0; i < rows.length(); ++i) {
				JSONObject c = rows.getJSONObject(i);
				data = app.Read("/token?type=1&id=" + Long.toString(c.getLong("id")), null);
				JSONObject t = new JSONObject(new String(data, "UTF-8"));
				app.Download(c.getLong("id"), 1, t.getString("token"), Long.toString(c.getLong("id")) + "-1k.wav");
				System.out.println(Long.toString(c.getLong("id")) + " ok");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}