Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.codehaus.jackson.annotate.JsonAutoDetect;
- import org.codehaus.jackson.annotate.JsonSetter;
- import org.codehaus.jackson.map.ObjectMapper;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- public class InstawalletClient {
- public InstawalletClient() {
- System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
- java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- }
- public InstawalletProto.Instawallet buildWallet() throws IOException {
- String wallet_id = getNewWallet();
- return buildWallet(wallet_id);
- }
- public InstawalletProto.Instawallet buildWallet(String wallet_id) throws IOException {
- String address = getAddress(wallet_id);
- long balance = getBalance(wallet_id);
- return InstawalletProto.Instawallet.newBuilder()
- .setId(wallet_id)
- .setAddress(address)
- .setBalance(balance)
- .setStatus(balance == 0 ? InstawalletProto.Instawallet.Status.NEW : InstawalletProto.Instawallet.Status.FILLED)
- .setTimestamp(System.currentTimeMillis())
- .build();
- }
- public String getNewWallet() throws IOException {
- InstawalletRequest<NewWalletResponse> request = new InstawalletRequest<NewWalletResponse>(null, "new_wallet");
- request.setRequestMethod("POST");
- return request.getResponseObject(NewWalletResponse.class).wallet_id;
- }
- public String getAddress(String wallet_id) throws IOException {
- InstawalletRequest<AddressResponse> request = new InstawalletRequest<AddressResponse>(wallet_id, "address");
- request.setRequestMethod("GET");
- return request.getResponseObject(AddressResponse.class).getAddress();
- }
- public long getBalance(String wallet_id) throws IOException {
- InstawalletRequest<BalanceResponse> request = new InstawalletRequest<BalanceResponse>(wallet_id, "balance");
- request.setRequestMethod("GET");
- return request.getResponseObject(BalanceResponse.class).getBalance();
- }
- public long sendPayment(String wallet_id, String address, double amount) throws IOException {
- return sendPayment(wallet_id, address, Math.round(amount * Math.pow(10, 8)));
- }
- public long sendPayment(String wallet_id, String address, long amount) throws IOException {
- InstawalletRequest<PaymentResponse> request = new InstawalletRequest<PaymentResponse>(wallet_id, "payment");
- request.setRequestMethod("POST");
- request.addArgument("amount", Long.toString(amount));
- request.addArgument("address", address);
- return request.getResponseObject(PaymentResponse.class).getMessage_code() == 0 ? amount : 0;
- }
- public byte[] getAddressQrCode(String wallet_id) throws IOException {
- InstawalletRequest request = new InstawalletRequest(wallet_id, "qrcode:address");
- request.setRequestMethod("GET");
- return request.getResponseBytes();
- }
- public byte[] getUrlQrCode(String wallet_id) throws IOException {
- InstawalletRequest request = new InstawalletRequest(wallet_id, "qrcode:link");
- request.setRequestMethod("GET");
- return request.getResponseBytes();
- }
- class InstawalletRequest<T extends InstwalletResponse> {
- Random random = new Random(System.currentTimeMillis());
- int backoff = 250;
- int ceiling = 5000;
- HttpURLConnection connection;
- URL url;
- String requestMethod;
- Map<String, String> arguments = new HashMap<String, String>();
- InstawalletRequest(String wallet_id, String call) throws IOException {
- String path;
- if (call.equals("new_wallet")) {
- path = "https://www.instawallet.org/api/v1/new_wallet";
- } else if (call.contains("qrcode:")) {
- path = String.format("https://www.instawallet.org/qrcode/%s/%s.png", call.replace("qrcode:", ""), wallet_id);
- } else {
- path = String.format("https://www.instawallet.org/api/v1/w/%s/%s", wallet_id, call);
- }
- //path = path.replace("https://www.instawallet.org", "http://127.0.0.1:8080");
- url = new URL(path);
- }
- void setRequestMethod(String requestMethod) {
- this.requestMethod = requestMethod;
- }
- void addArgument(String key, String value) {
- arguments.put(key, value);
- }
- HttpURLConnection getConnection() throws IOException {
- while (connection == null) {
- try {
- connection = (HttpURLConnection) url.openConnection();
- } catch (IOException e) {
- e.printStackTrace();
- backoff();
- }
- }
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setRequestMethod(requestMethod);
- OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
- writer.write(getData());
- writer.flush();
- writer.close();
- return connection;
- }
- String getData() throws UnsupportedEncodingException {
- StringBuilder builder = new StringBuilder();
- for(Map.Entry<String, String> argument : arguments.entrySet()) {
- if (builder.length() > 0) {
- builder.append("&");
- }
- builder.append(String.format("%s=%s", URLEncoder.encode(argument.getKey(), "utf-8"), URLEncoder.encode(argument.getValue(), "utf-8")));
- }
- return builder.toString();
- }
- InputStream getResponseStream() {
- InputStream stream = null;
- while (stream == null) {
- try {
- stream = getConnection().getInputStream();
- } catch (IOException e) {
- connection = null;
- e.printStackTrace();
- backoff();
- }
- }
- return stream;
- }
- byte[] getResponseBytes() throws IOException {
- InputStream inputStream = getResponseStream();
- int len;
- int size = 1024;
- byte[] buffer;
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- buffer = new byte[size];
- while ((len = inputStream.read(buffer, 0, size)) != -1) {
- outputStream.write(buffer, 0, len);
- }
- return outputStream.toByteArray();
- }
- T getResponseObject(Class<T> targetClass) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
- T response = mapper.readValue(getResponseStream(), targetClass);
- if (response.isSuccessful()) {
- return response;
- } else {
- throw new InstawalletAPIException(response);
- }
- }
- private void backoff() {
- try {
- Thread.sleep(random.nextInt(backoff));
- } catch (InterruptedException ignore) {
- }
- if (backoff < ceiling) {
- backoff *= 2;
- } else {
- backoff = ceiling;
- }
- }
- }
- // inner classes for json response objects
- static class InstwalletResponse {
- private boolean successful;
- public boolean isSuccessful() {
- return successful;
- }
- @JsonSetter
- public void setSuccessful(boolean successful) {
- this.successful = successful;
- }
- @Override
- public String toString() {
- return successful ? "successful" : "unsuccessful";
- }
- }
- static class NewWalletResponse extends InstwalletResponse {
- private String wallet_id;
- public String getWallet_id() {
- return wallet_id;
- }
- @JsonSetter
- public void setWallet_id(String wallet_id) {
- this.wallet_id = wallet_id;
- }
- @Override
- public String toString() {
- return String.format("%s (%s)", super.toString(), wallet_id);
- }
- }
- static class AddressResponse extends InstwalletResponse {
- private String address;
- public String getAddress() {
- return address;
- }
- @JsonSetter
- public void setAddress(String address) {
- this.address = address;
- }
- @Override
- public String toString() {
- return String.format("%s (%s)", super.toString(), address);
- }
- }
- static class BalanceResponse extends InstwalletResponse {
- private long balance;
- public long getBalance() {
- return balance;
- }
- @JsonSetter
- public void setBalance(long balance) {
- this.balance = balance;
- }
- @Override
- public String toString() {
- return String.format("%s (%s)", super.toString(), balance);
- }
- }
- static class PaymentResponse extends InstwalletResponse {
- private String message;
- private int message_code;
- public String getMessage() {
- return message;
- }
- @JsonSetter
- public void setMessage(String message) {
- this.message = message;
- }
- public int getMessage_code() {
- return message_code;
- }
- @JsonSetter
- public void setMessage_code(int message_code) {
- this.message_code = message_code;
- }
- @Override
- public String toString() {
- return String.format("%s (%d:%s)", super.toString(), message_code, message);
- }
- }
- private class InstawalletAPIException extends IOException {
- private final InstwalletResponse response;
- public InstawalletAPIException(InstwalletResponse response) {
- this.response = response;
- }
- @Override
- public String getMessage() {
- return response.toString();
- }
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append(String.format("Response type: %s\n", response.getClass().getName()));
- builder.append(String.format("Response message: %s", response.toString()));
- return builder.toString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement