Returns hex representation of bytes contained in this memo until null byte (0x00) is found.
+ *
+ *
Example:
+ *
+ * MemoHash memo = new MemoHash("4142434445");
+ * memo.getHexValue(); // 4142434445000000000000000000000000000000000000000000000000000000
+ * memo.getTrimmedHexValue(); // 4142434445
+ *
+ */
+ public String getTrimmedHexValue() {
+ return this.getHexValue().split("00")[0];
+ }
- @Override
- abstract kin.base.xdr.Memo toXdr();
+ @Override
+ abstract kin.base.xdr.Memo toXdr();
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- MemoHashAbstract that = (MemoHashAbstract) o;
- return Arrays.equals(bytes, that.bytes);
- }
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MemoHashAbstract that = (MemoHashAbstract) o;
+ return Arrays.equals(bytes, that.bytes);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
index 7ef4c75d..53703b45 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoId.java
@@ -7,35 +7,35 @@
* Represents MEMO_ID.
*/
public class MemoId extends Memo {
- private long id;
+ private long id;
- public MemoId(long id) {
- if (id < 0) {
- throw new IllegalArgumentException("id must be a positive number");
+ public MemoId(long id) {
+ if (id < 0) {
+ throw new IllegalArgumentException("id must be a positive number");
+ }
+ this.id = id;
}
- this.id = id;
- }
- public long getId() {
- return id;
- }
+ public long getId() {
+ return id;
+ }
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_ID);
- Uint64 idXdr = new Uint64();
- idXdr.setUint64(id);
- memo.setId(idXdr);
- return memo;
- }
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_ID);
+ Uint64 idXdr = new Uint64();
+ idXdr.setUint64(id);
+ memo.setId(idXdr);
+ return memo;
+ }
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- MemoId memoId = (MemoId) o;
- return id == memoId.id;
- }
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MemoId memoId = (MemoId) o;
+ return id == memoId.id;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
index b060919c..8c57b190 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoNone.java
@@ -6,17 +6,17 @@
* Represents MEMO_NONE.
*/
public class MemoNone extends Memo {
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_NONE);
- return memo;
- }
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_NONE);
+ return memo;
+ }
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- return true;
- }
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ return true;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
index 4ab4d208..caefda5b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoReturnHash.java
@@ -8,23 +8,23 @@
* Represents MEMO_RETURN.
*/
public class MemoReturnHash extends MemoHashAbstract {
- public MemoReturnHash(byte[] bytes) {
- super(bytes);
- }
+ public MemoReturnHash(byte[] bytes) {
+ super(bytes);
+ }
- public MemoReturnHash(String hexString) throws DecoderException {
- super(hexString);
- }
+ public MemoReturnHash(String hexString) throws DecoderException {
+ super(hexString);
+ }
- @Override
- Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_RETURN);
+ @Override
+ Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_RETURN);
- kin.base.xdr.Hash hash = new kin.base.xdr.Hash();
- hash.setHash(bytes);
+ kin.base.xdr.Hash hash = new kin.base.xdr.Hash();
+ hash.setHash(bytes);
- memo.setHash(hash);
- return memo;
- }
+ memo.setHash(hash);
+ return memo;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
index 4912794e..566c791d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoText.java
@@ -1,55 +1,56 @@
package kin.base;
-import static kin.base.Util.CHARSET_UTF8;
-import static kin.base.Util.checkNotNull;
-
import java.io.UnsupportedEncodingException;
+
import kin.base.xdr.MemoType;
+import static kin.base.Util.CHARSET_UTF8;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents MEMO_TEXT.
*/
public class MemoText extends Memo {
- private String text;
-
- public MemoText(String text) {
- this.text = checkNotNull(text, "text cannot be null");
-
- int length = 0;
- try {
- length = text.getBytes(CHARSET_UTF8).length;
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ private String text;
+
+ public MemoText(String text) {
+ this.text = checkNotNull(text, "text cannot be null");
+
+ int length = 0;
+ try {
+ length = text.getBytes(CHARSET_UTF8).length;
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ if (length > 28) {
+ throw new MemoTooLongException("text must be <= 28 bytes. length=" + String.valueOf(length));
+ }
}
- if (length > 28) {
- throw new MemoTooLongException("text must be <= 28 bytes. length=" + String.valueOf(length));
+
+ public String getText() {
+ return text;
}
- }
-
- public String getText() {
- return text;
- }
-
- @Override
- kin.base.xdr.Memo toXdr() {
- kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
- memo.setDiscriminant(MemoType.MEMO_TEXT);
- memo.setText(text);
- return memo;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- MemoText memoText = (MemoText) o;
- if (text == null && memoText.text == null) {
- return true;
+
+ @Override
+ kin.base.xdr.Memo toXdr() {
+ kin.base.xdr.Memo memo = new kin.base.xdr.Memo();
+ memo.setDiscriminant(MemoType.MEMO_TEXT);
+ memo.setText(text);
+ return memo;
}
- if (text != null && memoText!= null) {
- return text.equals(memoText.text);
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MemoText memoText = (MemoText) o;
+ if (text == null && memoText.text == null) {
+ return true;
+ }
+ if (text != null && memoText != null) {
+ return text.equals(memoText.text);
+ }
+ return false;
}
- return false;
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java b/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
index aaca3190..e4929c12 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/MemoTooLongException.java
@@ -2,6 +2,7 @@
/**
* Indicates that value passed to Memo
+ *
* @see Memo
*/
public class MemoTooLongException extends RuntimeException {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Network.java b/kin-sdk/kin-base/src/main/java/kin/base/Network.java
index a96bf8ed..8407fb0e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Network.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Network.java
@@ -1,10 +1,10 @@
package kin.base;
+import java.io.UnsupportedEncodingException;
+
import static kin.base.Util.CHARSET_UTF8;
import static kin.base.Util.checkNotNull;
-import java.io.UnsupportedEncodingException;
-
/**
* Network class is used to specify which Stellar network you want to use.
* Each network has a networkPassphrase which is hashed to
@@ -13,75 +13,75 @@
* {@link Network#use(Network)}, {@link Network#usePublicNetwork()} or {@link Network#useTestNetwork()}.
*/
public class Network {
- private final static String PUBLIC = "Public Global Stellar Network ; September 2015";
- private final static String TESTNET = "Test SDF Network ; September 2015";
- private static Network current;
+ private final static String PUBLIC = "Public Global Stellar Network ; September 2015";
+ private final static String TESTNET = "Test SDF Network ; September 2015";
+ private static Network current;
- private final String networkPassphrase;
+ private final String networkPassphrase;
- /**
- * Creates a new Network object to represent a network with a given passphrase
- *
- * @param networkPassphrase
- */
- public Network(String networkPassphrase) {
- this.networkPassphrase = checkNotNull(networkPassphrase, "networkPassphrase cannot be null");
- }
+ /**
+ * Creates a new Network object to represent a network with a given passphrase
+ *
+ * @param networkPassphrase
+ */
+ public Network(String networkPassphrase) {
+ this.networkPassphrase = checkNotNull(networkPassphrase, "networkPassphrase cannot be null");
+ }
- /**
- * Returns network passphrase
- */
- public String getNetworkPassphrase() {
- return networkPassphrase;
- }
+ /**
+ * Returns network passphrase
+ */
+ public String getNetworkPassphrase() {
+ return networkPassphrase;
+ }
- /**
- * Returns network id (SHA-256 hashed networkPassphrase).
- */
- public byte[] getNetworkId() {
- try {
- return Util.hash(current.getNetworkPassphrase().getBytes(CHARSET_UTF8));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- return null;
+ /**
+ * Returns network id (SHA-256 hashed networkPassphrase).
+ */
+ public byte[] getNetworkId() {
+ try {
+ return Util.hash(current.getNetworkPassphrase().getBytes(CHARSET_UTF8));
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ return null;
+ }
}
- }
- /**
- * Returns currently used Network object.
- */
- public static Network current() {
- return current;
- }
+ /**
+ * Returns currently used Network object.
+ */
+ public static Network current() {
+ return current;
+ }
- /**
- * Use network as a current network.
- *
- * @param network Network object to set as current network
- */
- public static void use(Network network) {
- current = network;
- }
+ /**
+ * Use network as a current network.
+ *
+ * @param network Network object to set as current network
+ */
+ public static void use(Network network) {
+ current = network;
+ }
- /**
- * Use Stellar Public Network
- */
- public static void usePublicNetwork() {
- Network.use(getPublicNetwork());
- }
+ /**
+ * Use Stellar Public Network
+ */
+ public static void usePublicNetwork() {
+ Network.use(getPublicNetwork());
+ }
- /**
- * Use Stellar Test Network.
- */
- public static void useTestNetwork() {
- Network.use(getTestNetwork());
- }
+ /**
+ * Use Stellar Test Network.
+ */
+ public static void useTestNetwork() {
+ Network.use(getTestNetwork());
+ }
- public static Network getPublicNetwork() {
- return new Network(PUBLIC);
- }
+ public static Network getPublicNetwork() {
+ return new Network(PUBLIC);
+ }
- public static Network getTestNetwork() {
- return new Network(TESTNET);
- }
+ public static Network getTestNetwork() {
+ return new Network(TESTNET);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java b/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
index abe0945a..a35fd09d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/NoNetworkSelectedException.java
@@ -4,7 +4,7 @@
* Indicates that no network was selected.
*/
public class NoNetworkSelectedException extends RuntimeException {
- public NoNetworkSelectedException() {
- super("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
- }
+ public NoNetworkSelectedException() {
+ super("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Operation.java b/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
index f462af62..a07246cf 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Operation.java
@@ -1,130 +1,135 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
+
import kin.base.codec.Base64;
import kin.base.xdr.AccountID;
import kin.base.xdr.XdrDataOutputStream;
+import static kin.base.Util.checkNotNull;
+
/**
* Abstract class for operations.
*/
public abstract class Operation {
- Operation() {}
-
- private KeyPair mSourceAccount;
+ Operation() {
+ }
- private static final BigDecimal ONE = new BigDecimal(10).pow(5);
+ private KeyPair mSourceAccount;
- protected static long toXdrAmount(String value) {
- value = checkNotNull(value, "value cannot be null");
- BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE);
- return amount.longValueExact();
- }
+ private static final BigDecimal ONE = new BigDecimal(10).pow(5);
- protected static String fromXdrAmount(long value) {
- BigDecimal amount = new BigDecimal(value).divide(Operation.ONE);
- return amount.toPlainString();
- }
+ protected static long toXdrAmount(String value) {
+ value = checkNotNull(value, "value cannot be null");
+ BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE);
+ return amount.longValueExact();
+ }
- /**
- * Generates Operation XDR object.
- */
- public kin.base.xdr.Operation toXdr() {
- kin.base.xdr.Operation xdr = new kin.base.xdr.Operation();
- if (getSourceAccount() != null) {
- AccountID sourceAccount = new AccountID();
- sourceAccount.setAccountID(getSourceAccount().getXdrPublicKey());
- xdr.setSourceAccount(sourceAccount);
+ protected static String fromXdrAmount(long value) {
+ BigDecimal amount = new BigDecimal(value).divide(Operation.ONE);
+ return amount.toPlainString();
}
- xdr.setBody(toOperationBody());
- return xdr;
- }
- /**
- * Returns base64-encoded Operation XDR object.
- */
- public String toXdrBase64() {
- try {
- kin.base.xdr.Operation operation = this.toXdr();
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
- kin.base.xdr.Operation.encode(xdrOutputStream, operation);
- Base64 base64Codec = new Base64();
- return base64Codec.encodeAsString(outputStream.toByteArray());
- } catch (IOException e) {
- throw new AssertionError(e);
+ /**
+ * Generates Operation XDR object.
+ */
+ public kin.base.xdr.Operation toXdr() {
+ kin.base.xdr.Operation xdr = new kin.base.xdr.Operation();
+ if (getSourceAccount() != null) {
+ AccountID sourceAccount = new AccountID();
+ sourceAccount.setAccountID(getSourceAccount().getXdrPublicKey());
+ xdr.setSourceAccount(sourceAccount);
+ }
+ xdr.setBody(toOperationBody());
+ return xdr;
}
- }
- /**
- * Returns new Operation object from Operation XDR object.
- * @param xdr XDR object
- */
- public static Operation fromXdr(kin.base.xdr.Operation xdr) {
- kin.base.xdr.Operation.OperationBody body = xdr.getBody();
- Operation operation;
- switch (body.getDiscriminant()) {
- case CREATE_ACCOUNT:
- operation = new CreateAccountOperation.Builder(body.getCreateAccountOp()).build();
- break;
- case PAYMENT:
- operation = new PaymentOperation.Builder(body.getPaymentOp()).build();
- break;
- case PATH_PAYMENT:
- operation = new PathPaymentOperation.Builder(body.getPathPaymentOp()).build();
- break;
- case MANAGE_OFFER:
- operation = new ManageOfferOperation.Builder(body.getManageOfferOp()).build();
- break;
- case CREATE_PASSIVE_OFFER:
- operation = new CreatePassiveOfferOperation.Builder(body.getCreatePassiveOfferOp()).build();
- break;
- case SET_OPTIONS:
- operation = new SetOptionsOperation.Builder(body.getSetOptionsOp()).build();
- break;
- case CHANGE_TRUST:
- operation = new ChangeTrustOperation.Builder(body.getChangeTrustOp()).build();
- break;
- case ALLOW_TRUST:
- operation = new AllowTrustOperation.Builder(body.getAllowTrustOp()).build();
- break;
- case ACCOUNT_MERGE:
- operation = new AccountMergeOperation.Builder(body).build();
- break;
- case MANAGE_DATA:
- operation = new ManageDataOperation.Builder(body.getManageDataOp()).build();
- break;
- default:
- throw new RuntimeException("Unknown operation body " + body.getDiscriminant());
+ /**
+ * Returns base64-encoded Operation XDR object.
+ */
+ public String toXdrBase64() {
+ try {
+ kin.base.xdr.Operation operation = this.toXdr();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
+ kin.base.xdr.Operation.encode(xdrOutputStream, operation);
+ Base64 base64Codec = new Base64();
+ return base64Codec.encodeAsString(outputStream.toByteArray());
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
}
- if (xdr.getSourceAccount() != null) {
- operation.setSourceAccount(KeyPair.fromXdrPublicKey(xdr.getSourceAccount().getAccountID()));
+
+ /**
+ * Returns new Operation object from Operation XDR object.
+ *
+ * @param xdr XDR object
+ */
+ public static Operation fromXdr(kin.base.xdr.Operation xdr) {
+ kin.base.xdr.Operation.OperationBody body = xdr.getBody();
+ Operation operation;
+ switch (body.getDiscriminant()) {
+ case CREATE_ACCOUNT:
+ operation = new CreateAccountOperation.Builder(body.getCreateAccountOp()).build();
+ break;
+ case PAYMENT:
+ operation = new PaymentOperation.Builder(body.getPaymentOp()).build();
+ break;
+ case PATH_PAYMENT:
+ operation = new PathPaymentOperation.Builder(body.getPathPaymentOp()).build();
+ break;
+ case MANAGE_OFFER:
+ operation = new ManageOfferOperation.Builder(body.getManageOfferOp()).build();
+ break;
+ case CREATE_PASSIVE_OFFER:
+ operation = new CreatePassiveOfferOperation.Builder(body.getCreatePassiveOfferOp()).build();
+ break;
+ case SET_OPTIONS:
+ operation = new SetOptionsOperation.Builder(body.getSetOptionsOp()).build();
+ break;
+ case CHANGE_TRUST:
+ operation = new ChangeTrustOperation.Builder(body.getChangeTrustOp()).build();
+ break;
+ case ALLOW_TRUST:
+ operation = new AllowTrustOperation.Builder(body.getAllowTrustOp()).build();
+ break;
+ case ACCOUNT_MERGE:
+ operation = new AccountMergeOperation.Builder(body).build();
+ break;
+ case MANAGE_DATA:
+ operation = new ManageDataOperation.Builder(body.getManageDataOp()).build();
+ break;
+ default:
+ throw new RuntimeException("Unknown operation body " + body.getDiscriminant());
+ }
+ if (xdr.getSourceAccount() != null) {
+ operation.setSourceAccount(KeyPair.fromXdrPublicKey(xdr.getSourceAccount().getAccountID()));
+ }
+ return operation;
}
- return operation;
- }
- /**
- * Returns operation source account.
- */
- public KeyPair getSourceAccount() {
- return mSourceAccount;
- }
+ /**
+ * Returns operation source account.
+ */
+ public KeyPair getSourceAccount() {
+ return mSourceAccount;
+ }
- /**
- * Sets operation source account.
- * @param keypair
- */
- void setSourceAccount(KeyPair keypair) {
- mSourceAccount = checkNotNull(keypair, "keypair cannot be null");
- }
+ /**
+ * Sets operation source account.
+ *
+ * @param keypair
+ */
+ void setSourceAccount(KeyPair keypair) {
+ mSourceAccount = checkNotNull(keypair, "keypair cannot be null");
+ }
- /**
- * Generates OperationBody XDR object
- * @return OperationBody XDR object
- */
- abstract kin.base.xdr.Operation.OperationBody toOperationBody();
+ /**
+ * Generates OperationBody XDR object
+ *
+ * @return OperationBody XDR object
+ */
+ abstract kin.base.xdr.Operation.OperationBody toOperationBody();
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
index d79dac81..4a45fc96 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/PathPaymentOperation.java
@@ -1,193 +1,198 @@
package kin.base;
-import static kin.base.Util.checkArgument;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
import kin.base.xdr.PathPaymentOp;
+import static kin.base.Util.checkArgument;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents PathPayment operation.
+ *
* @see List of Operations
*/
public class PathPaymentOperation extends Operation {
- private final Asset sendAsset;
- private final String sendMax;
- private final KeyPair destination;
- private final Asset destAsset;
- private final String destAmount;
- private final Asset[] path;
-
- private PathPaymentOperation(Asset sendAsset, String sendMax, KeyPair destination,
- Asset destAsset, String destAmount, Asset[] path) {
- this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null");
- this.sendMax = checkNotNull(sendMax, "sendMax cannot be null");
- this.destination = checkNotNull(destination, "destination cannot be null");
- this.destAsset = checkNotNull(destAsset, "destAsset cannot be null");
- this.destAmount = checkNotNull(destAmount, "destAmount cannot be null");
- if (path == null) {
- this.path = new Asset[0];
- } else {
- checkArgument(path.length <= 5, "The maximum number of assets in the path is 5");
- this.path = path;
- }
- }
-
- /**
- * The asset deducted from the sender's account.
- */
- public Asset getSendAsset() {
- return sendAsset;
- }
-
- /**
- * The maximum amount of send asset to deduct (excluding fees)
- */
- public String getSendMax() {
- return sendMax;
- }
-
- /**
- * Account that receives the payment.
- */
- public KeyPair getDestination() {
- return destination;
- }
-
- /**
- * The asset the destination account receives.
- */
- public Asset getDestAsset() {
- return destAsset;
- }
-
- /**
- * The amount of destination asset the destination account receives.
- */
- public String getDestAmount() {
- return destAmount;
- }
-
- /**
- * The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path would contain XLM and BTC.
- */
- public Asset[] getPath() {
- return path;
- }
-
- @Override
- kin.base.xdr.Operation.OperationBody toOperationBody() {
- PathPaymentOp op = new PathPaymentOp();
-
- // sendAsset
- op.setSendAsset(sendAsset.toXdr());
- // sendMax
- Int64 sendMax = new Int64();
- sendMax.setInt64(Operation.toXdrAmount(this.sendMax));
- op.setSendMax(sendMax);
- // destination
- AccountID destination = new AccountID();
- destination.setAccountID(this.destination.getXdrPublicKey());
- op.setDestination(destination);
- // destAsset
- op.setDestAsset(destAsset.toXdr());
- // destAmount
- Int64 destAmount = new Int64();
- destAmount.setInt64(Operation.toXdrAmount(this.destAmount));
- op.setDestAmount(destAmount);
- // path
- kin.base.xdr.Asset[] path = new kin.base.xdr.Asset[this.path.length];
- for (int i = 0; i < this.path.length; i++) {
- path[i] = this.path[i].toXdr();
- }
- op.setPath(path);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
- body.setDiscriminant(OperationType.PATH_PAYMENT);
- body.setPathPaymentOp(op);
- return body;
- }
-
- /**
- * Builds PathPayment operation.
- * @see PathPaymentOperation
- */
- public static class Builder {
private final Asset sendAsset;
private final String sendMax;
private final KeyPair destination;
private final Asset destAsset;
private final String destAmount;
- private Asset[] path;
-
- private KeyPair mSourceAccount;
-
- Builder(PathPaymentOp op) {
- sendAsset = Asset.fromXdr(op.getSendAsset());
- sendMax = Operation.fromXdrAmount(op.getSendMax().getInt64().longValue());
- destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
- destAsset = Asset.fromXdr(op.getDestAsset());
- destAmount = Operation.fromXdrAmount(op.getDestAmount().getInt64().longValue());
- path = new Asset[op.getPath().length];
- for (int i = 0; i < op.getPath().length; i++) {
- path[i] = Asset.fromXdr(op.getPath()[i]);
- }
+ private final Asset[] path;
+
+ private PathPaymentOperation(Asset sendAsset, String sendMax, KeyPair destination,
+ Asset destAsset, String destAmount, Asset[] path) {
+ this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null");
+ this.sendMax = checkNotNull(sendMax, "sendMax cannot be null");
+ this.destination = checkNotNull(destination, "destination cannot be null");
+ this.destAsset = checkNotNull(destAsset, "destAsset cannot be null");
+ this.destAmount = checkNotNull(destAmount, "destAmount cannot be null");
+ if (path == null) {
+ this.path = new Asset[0];
+ } else {
+ checkArgument(path.length <= 5, "The maximum number of assets in the path is 5");
+ this.path = path;
+ }
+ }
+
+ /**
+ * The asset deducted from the sender's account.
+ */
+ public Asset getSendAsset() {
+ return sendAsset;
+ }
+
+ /**
+ * The maximum amount of send asset to deduct (excluding fees)
+ */
+ public String getSendMax() {
+ return sendMax;
}
/**
- * Creates a new PathPaymentOperation builder.
- * @param sendAsset The asset deducted from the sender's account.
- * @param sendMax The asset deducted from the sender's account.
- * @param destination Payment destination
- * @param destAsset The asset the destination account receives.
- * @param destAmount The amount of destination asset the destination account receives.
- * @throws ArithmeticException when sendMax or destAmount has more than 7 decimal places.
+ * Account that receives the payment.
*/
- public Builder(Asset sendAsset, String sendMax, KeyPair destination,
- Asset destAsset, String destAmount) {
- this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null");
- this.sendMax = checkNotNull(sendMax, "sendMax cannot be null");
- this.destination = checkNotNull(destination, "destination cannot be null");
- this.destAsset = checkNotNull(destAsset, "destAsset cannot be null");
- this.destAmount = checkNotNull(destAmount, "destAmount cannot be null");
+ public KeyPair getDestination() {
+ return destination;
}
/**
- * Sets path for this operation
- * @param path The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path field would contain XLM and BTC.
- * @return Builder object so you can chain methods.
+ * The asset the destination account receives.
*/
- public Builder setPath(Asset[] path) {
- checkNotNull(path, "path cannot be null");
- checkArgument(path.length <= 5, "The maximum number of assets in the path is 5");
- this.path = path;
- return this;
+ public Asset getDestAsset() {
+ return destAsset;
}
/**
- * Sets the source account for this operation.
- * @param sourceAccount The operation's source account.
- * @return Builder object so you can chain methods.
+ * The amount of destination asset the destination account receives.
*/
- public Builder setSourceAccount(KeyPair sourceAccount) {
- mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
- return this;
+ public String getDestAmount() {
+ return destAmount;
+ }
+
+ /**
+ * The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path would contain XLM and BTC.
+ */
+ public Asset[] getPath() {
+ return path;
+ }
+
+ @Override
+ kin.base.xdr.Operation.OperationBody toOperationBody() {
+ PathPaymentOp op = new PathPaymentOp();
+
+ // sendAsset
+ op.setSendAsset(sendAsset.toXdr());
+ // sendMax
+ Int64 sendMax = new Int64();
+ sendMax.setInt64(Operation.toXdrAmount(this.sendMax));
+ op.setSendMax(sendMax);
+ // destination
+ AccountID destination = new AccountID();
+ destination.setAccountID(this.destination.getXdrPublicKey());
+ op.setDestination(destination);
+ // destAsset
+ op.setDestAsset(destAsset.toXdr());
+ // destAmount
+ Int64 destAmount = new Int64();
+ destAmount.setInt64(Operation.toXdrAmount(this.destAmount));
+ op.setDestAmount(destAmount);
+ // path
+ kin.base.xdr.Asset[] path = new kin.base.xdr.Asset[this.path.length];
+ for (int i = 0; i < this.path.length; i++) {
+ path[i] = this.path[i].toXdr();
+ }
+ op.setPath(path);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.PATH_PAYMENT);
+ body.setPathPaymentOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds PathPayment operation.
+ *
+ * @see PathPaymentOperation
*/
- public PathPaymentOperation build() {
- PathPaymentOperation operation = new PathPaymentOperation(sendAsset, sendMax, destination,
- destAsset, destAmount, path);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ public static class Builder {
+ private final Asset sendAsset;
+ private final String sendMax;
+ private final KeyPair destination;
+ private final Asset destAsset;
+ private final String destAmount;
+ private Asset[] path;
+
+ private KeyPair mSourceAccount;
+
+ Builder(PathPaymentOp op) {
+ sendAsset = Asset.fromXdr(op.getSendAsset());
+ sendMax = Operation.fromXdrAmount(op.getSendMax().getInt64().longValue());
+ destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
+ destAsset = Asset.fromXdr(op.getDestAsset());
+ destAmount = Operation.fromXdrAmount(op.getDestAmount().getInt64().longValue());
+ path = new Asset[op.getPath().length];
+ for (int i = 0; i < op.getPath().length; i++) {
+ path[i] = Asset.fromXdr(op.getPath()[i]);
+ }
+ }
+
+ /**
+ * Creates a new PathPaymentOperation builder.
+ *
+ * @param sendAsset The asset deducted from the sender's account.
+ * @param sendMax The asset deducted from the sender's account.
+ * @param destination Payment destination
+ * @param destAsset The asset the destination account receives.
+ * @param destAmount The amount of destination asset the destination account receives.
+ * @throws ArithmeticException when sendMax or destAmount has more than 7 decimal places.
+ */
+ public Builder(Asset sendAsset, String sendMax, KeyPair destination,
+ Asset destAsset, String destAmount) {
+ this.sendAsset = checkNotNull(sendAsset, "sendAsset cannot be null");
+ this.sendMax = checkNotNull(sendMax, "sendMax cannot be null");
+ this.destination = checkNotNull(destination, "destination cannot be null");
+ this.destAsset = checkNotNull(destAsset, "destAsset cannot be null");
+ this.destAmount = checkNotNull(destAmount, "destAmount cannot be null");
+ }
+
+ /**
+ * Sets path for this operation
+ *
+ * @param path The assets (other than send asset and destination asset) involved in the offers the path takes. For example, if you can only find a path from USD to EUR through XLM and BTC, the path would be USD -» XLM -» BTC -» EUR and the path field would contain XLM and BTC.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setPath(Asset[] path) {
+ checkNotNull(path, "path cannot be null");
+ checkArgument(path.length <= 5, "The maximum number of assets in the path is 5");
+ this.path = path;
+ return this;
+ }
+
+ /**
+ * Sets the source account for this operation.
+ *
+ * @param sourceAccount The operation's source account.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setSourceAccount(KeyPair sourceAccount) {
+ mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
+ return this;
+ }
+
+ /**
+ * Builds an operation
+ */
+ public PathPaymentOperation build() {
+ PathPaymentOperation operation = new PathPaymentOperation(sendAsset, sendMax, destination,
+ destAsset, destAmount, path);
+ if (mSourceAccount != null) {
+ operation.setSourceAccount(mSourceAccount);
+ }
+ return operation;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
index 29aaee65..584424f7 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/PaymentOperation.java
@@ -1,123 +1,128 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.Int64;
import kin.base.xdr.OperationType;
import kin.base.xdr.PaymentOp;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents Payment operation.
+ *
* @see List of Operations
*/
public class PaymentOperation extends Operation {
- private final KeyPair destination;
- private final Asset asset;
- private final String amount;
-
- private PaymentOperation(KeyPair destination, Asset asset, String amount) {
- this.destination = checkNotNull(destination, "destination cannot be null");
- this.asset = checkNotNull(asset, "asset cannot be null");
- this.amount = checkNotNull(amount, "amount cannot be null");
- }
-
- /**
- * Account that receives the payment.
- */
- public KeyPair getDestination() {
- return destination;
- }
-
- /**
- * Asset to send to the destination account.
- */
- public Asset getAsset() {
- return asset;
- }
-
- /**
- * Amount of the asset to send.
- */
- public String getAmount() {
- return amount;
- }
-
- @Override
- kin.base.xdr.Operation.OperationBody toOperationBody() {
- PaymentOp op = new PaymentOp();
-
- // destination
- AccountID destination = new AccountID();
- destination.setAccountID(this.destination.getXdrPublicKey());
- op.setDestination(destination);
- // asset
- op.setAsset(asset.toXdr());
- // amount
- Int64 amount = new Int64();
- amount.setInt64(Operation.toXdrAmount(this.amount));
- op.setAmount(amount);
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
- body.setDiscriminant(OperationType.PAYMENT);
- body.setPaymentOp(op);
- return body;
- }
-
- /**
- * Builds Payment operation.
- * @see PathPaymentOperation
- */
- public static class Builder {
private final KeyPair destination;
private final Asset asset;
private final String amount;
- private KeyPair mSourceAccount;
+ private PaymentOperation(KeyPair destination, Asset asset, String amount) {
+ this.destination = checkNotNull(destination, "destination cannot be null");
+ this.asset = checkNotNull(asset, "asset cannot be null");
+ this.amount = checkNotNull(amount, "amount cannot be null");
+ }
/**
- * Construct a new PaymentOperation builder from a PaymentOp XDR.
- * @param op {@link PaymentOp}
+ * Account that receives the payment.
*/
- Builder(PaymentOp op) {
- destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
- asset = Asset.fromXdr(op.getAsset());
- amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue());
+ public KeyPair getDestination() {
+ return destination;
}
/**
- * Creates a new PaymentOperation builder.
- * @param destination The destination keypair (uses only the public key).
- * @param asset The asset to send.
- * @param amount The amount to send in lumens.
- * @throws ArithmeticException when amount has more than 7 decimal places.
+ * Asset to send to the destination account.
*/
- public Builder(KeyPair destination, Asset asset, String amount) {
- this.destination = destination;
- this.asset = asset;
- this.amount = amount;
+ public Asset getAsset() {
+ return asset;
}
/**
- * Sets the source account for this operation.
- * @param account The operation's source account.
- * @return Builder object so you can chain methods.
+ * Amount of the asset to send.
*/
- public Builder setSourceAccount(KeyPair account) {
- mSourceAccount = account;
- return this;
+ public String getAmount() {
+ return amount;
+ }
+
+ @Override
+ kin.base.xdr.Operation.OperationBody toOperationBody() {
+ PaymentOp op = new PaymentOp();
+
+ // destination
+ AccountID destination = new AccountID();
+ destination.setAccountID(this.destination.getXdrPublicKey());
+ op.setDestination(destination);
+ // asset
+ op.setAsset(asset.toXdr());
+ // amount
+ Int64 amount = new Int64();
+ amount.setInt64(Operation.toXdrAmount(this.amount));
+ op.setAmount(amount);
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.PAYMENT);
+ body.setPaymentOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds Payment operation.
+ *
+ * @see PathPaymentOperation
*/
- public PaymentOperation build() {
- PaymentOperation operation = new PaymentOperation(destination, asset, amount);
- if (mSourceAccount != null) {
- operation.setSourceAccount(mSourceAccount);
- }
- return operation;
+ public static class Builder {
+ private final KeyPair destination;
+ private final Asset asset;
+ private final String amount;
+
+ private KeyPair mSourceAccount;
+
+ /**
+ * Construct a new PaymentOperation builder from a PaymentOp XDR.
+ *
+ * @param op {@link PaymentOp}
+ */
+ Builder(PaymentOp op) {
+ destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
+ asset = Asset.fromXdr(op.getAsset());
+ amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue());
+ }
+
+ /**
+ * Creates a new PaymentOperation builder.
+ *
+ * @param destination The destination keypair (uses only the public key).
+ * @param asset The asset to send.
+ * @param amount The amount to send in lumens.
+ * @throws ArithmeticException when amount has more than 7 decimal places.
+ */
+ public Builder(KeyPair destination, Asset asset, String amount) {
+ this.destination = destination;
+ this.asset = asset;
+ this.amount = amount;
+ }
+
+ /**
+ * Sets the source account for this operation.
+ *
+ * @param account The operation's source account.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setSourceAccount(KeyPair account) {
+ mSourceAccount = account;
+ return this;
+ }
+
+ /**
+ * Builds an operation
+ */
+ public PaymentOperation build() {
+ PaymentOperation operation = new PaymentOperation(destination, asset, amount);
+ if (mSourceAccount != null) {
+ operation.setSourceAccount(mSourceAccount);
+ }
+ return operation;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Price.java b/kin-sdk/kin-base/src/main/java/kin/base/Price.java
index e3fa8830..a7d7ee8b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Price.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Price.java
@@ -1,13 +1,15 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.annotations.SerializedName;
+
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
+
import kin.base.xdr.Int32;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents Price. Price in Stellar is represented as a fraction.
*/
@@ -19,6 +21,7 @@ public class Price {
/**
* Create a new price. Price in Stellar is represented as a fraction.
+ *
* @param n numerator
* @param d denominator
*/
@@ -45,6 +48,7 @@ public int getDenominator() {
* Approximates price to a fraction.
* Please remember that this function can give unexpected results for values that cannot be represented as a
* fraction with 32-bit numerator and denominator. It's safer to create a Price object using the constructor.
+ *
* @param price Ex. "1.25"
*/
public static Price fromString(String price) {
@@ -75,8 +79,8 @@ public static Price fromString(String price) {
number = new BigDecimal(1).divide(f, 20, BigDecimal.ROUND_HALF_UP);
i = i + 1;
}
- BigDecimal n = fractions.get(fractions.size()-1)[0];
- BigDecimal d = fractions.get(fractions.size()-1)[1];
+ BigDecimal n = fractions.get(fractions.size() - 1)[0];
+ BigDecimal d = fractions.get(fractions.size() - 1)[1];
return new Price(n.intValue(), d.intValue());
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Server.java b/kin-sdk/kin-base/src/main/java/kin/base/Server.java
index 6a0228ad..cf99e970 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Server.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Server.java
@@ -1,12 +1,11 @@
package kin.base;
-import android.net.Uri;
-import android.net.Uri.Builder;
-import android.text.TextUtils;
import java.io.IOException;
+import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.concurrent.TimeUnit;
+import java.net.URL;
+
import kin.base.requests.AccountsRequestBuilder;
import kin.base.requests.EffectsRequestBuilder;
import kin.base.requests.LedgersRequestBuilder;
@@ -20,7 +19,7 @@
import kin.base.responses.GsonSingleton;
import kin.base.responses.SubmitTransactionResponse;
import okhttp3.FormBody;
-import okhttp3.Interceptor;
+import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@@ -34,7 +33,6 @@ public class Server {
private static final int TEMPORARY_REDIRECT = 307;
private static final String LOCATION_HEADER = "Location";
- private static final String KIN_SDK_ANDROID_VERSION_HEADER = "kin-sdk-android-version";
private URI serverURI;
@@ -55,23 +53,19 @@ public Server(String uri) {
*
Increase timeout to prevent timeout exception for transaction with ledger close
* time above default of 10 sec
*
- * @param uri Horizon server uri
- * @param transactionsTimeout transactions timeout value
- * @param timeUnit transactions timeout unit
+ * @param uri Horizon server uri
+ * @param client OkHttpClient
*/
- public Server(String uri, int transactionsTimeout, TimeUnit timeUnit) {
+ public Server(String uri, OkHttpClient client) {
createUri(uri);
- httpClient = new OkHttpClient.Builder()
- .connectTimeout(transactionsTimeout, timeUnit)
- .writeTimeout(transactionsTimeout, timeUnit)
- .readTimeout(transactionsTimeout, timeUnit)
- .addInterceptor(new HeaderInterceptor())
- .build();
+ httpClient = client;
}
private void createUri(String uri) {
try {
- serverURI = new URI(uri);
+ serverURI = new URL(uri).toURI();
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
@@ -151,19 +145,19 @@ public TransactionsRequestBuilder transactions() {
* Submits transaction to the network.
*
* @param transaction transaction to submit to the network.
- * @param url if supplied then use this url instead of the serverURI member and don't append anything to it.
+ * @param url if supplied then use this url instead of the serverURI member and don't append anything to it.
* @return {@link SubmitTransactionResponse}
*/
private SubmitTransactionResponse submitTransaction(Transaction transaction, String url) throws IOException {
- Uri transactionsUri = getUri(url);
+ URI transactionsUri = getUri(url);
RequestBody formBody = new FormBody.Builder()
- .add("tx", transaction.toEnvelopeXdrBase64())
- .build();
+ .add("tx", transaction.toEnvelopeXdrBase64())
+ .build();
Request request = new Request.Builder()
- .url(transactionsUri.toString())
- .post(formBody)
- .build();
+ .url(transactionsUri.toString())
+ .post(formBody)
+ .build();
Response response = null;
try {
@@ -199,14 +193,15 @@ public SubmitTransactionResponse submitTransaction(Transaction transaction) thro
return submitTransaction(transaction, null);
}
- private Uri getUri(String url) {
- boolean urlIsEmpty = TextUtils.isEmpty(url);
+ private URI getUri(String url) {
+ boolean urlIsEmpty = url == null || url.length() == 0;
String serverUrl = urlIsEmpty ? serverURI.toString() : url;
- Builder uriBuilder = Uri.parse(serverUrl).buildUpon();
+
+ HttpUrl.Builder uriBuilder = HttpUrl.get(URI.create(serverUrl)).newBuilder();
if (urlIsEmpty) {
- uriBuilder.appendPath("transactions");
+ uriBuilder.addPathSegment("transactions").build().url();
}
- return uriBuilder.build();
+ return uriBuilder.build().uri();
}
/**
@@ -215,16 +210,4 @@ private Uri getUri(String url) {
void setHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
-
- private class HeaderInterceptor implements Interceptor {
-
- @Override
- public Response intercept(Chain chain) throws IOException {
- Request request = chain.request();
- request = request.newBuilder()
- .addHeader(KIN_SDK_ANDROID_VERSION_HEADER, BuildConfig.VERSION_NAME)
- .build();
- return chain.proceed(request);
- }
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/SetOptionsOperation.java b/kin-sdk/kin-base/src/main/java/kin/base/SetOptionsOperation.java
index 2b3ddfe8..ef461fb4 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/SetOptionsOperation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/SetOptionsOperation.java
@@ -1,7 +1,5 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.AccountID;
import kin.base.xdr.OperationType;
import kin.base.xdr.SetOptionsOp;
@@ -9,340 +7,355 @@
import kin.base.xdr.String32;
import kin.base.xdr.Uint32;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents SetOptions operation.
+ *
* @see List of Operations
*/
public class SetOptionsOperation extends Operation {
- private final KeyPair inflationDestination;
- private final Integer clearFlags;
- private final Integer setFlags;
- private final Integer masterKeyWeight;
- private final Integer lowThreshold;
- private final Integer mediumThreshold;
- private final Integer highThreshold;
- private final String homeDomain;
- private final SignerKey signer;
- private final Integer signerWeight;
-
- private SetOptionsOperation(KeyPair inflationDestination, Integer clearFlags, Integer setFlags,
- Integer masterKeyWeight, Integer lowThreshold, Integer mediumThreshold,
- Integer highThreshold, String homeDomain, SignerKey signer, Integer signerWeight) {
- this.inflationDestination = inflationDestination;
- this.clearFlags = clearFlags;
- this.setFlags = setFlags;
- this.masterKeyWeight = masterKeyWeight;
- this.lowThreshold = lowThreshold;
- this.mediumThreshold = mediumThreshold;
- this.highThreshold = highThreshold;
- this.homeDomain = homeDomain;
- this.signer = signer;
- this.signerWeight = signerWeight;
- }
-
- /**
- * Account of the inflation destination.
- */
- public KeyPair getInflationDestination() {
- return inflationDestination;
- }
-
- /**
- * Indicates which flags to clear. For details about the flags, please refer to the accounts doc.
- * You can also use {@link AccountFlag} enum.
- */
- public Integer getClearFlags() {
- return clearFlags;
- }
-
- /**
- * Indicates which flags to set. For details about the flags, please refer to the accounts doc.
- * You can also use {@link AccountFlag} enum.
- */
- public Integer getSetFlags() {
- return setFlags;
- }
-
- /**
- * Weight of the master key.
- */
- public Integer getMasterKeyWeight() {
- return masterKeyWeight;
- }
-
- /**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold.
- */
- public Integer getLowThreshold() {
- return lowThreshold;
- }
-
- /**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold.
- */
- public Integer getMediumThreshold() {
- return mediumThreshold;
- }
-
- /**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold.
- */
- public Integer getHighThreshold() {
- return highThreshold;
- }
-
- /**
- * The home domain of an account.
- */
- public String getHomeDomain() {
- return homeDomain;
- }
-
- /**
- * Additional signer added/removed in this operation.
- */
- public SignerKey getSigner() {
- return signer;
- }
-
- /**
- * Additional signer weight. The signer is deleted if the weight is 0.
- */
- public Integer getSignerWeight() {
- return signerWeight;
- }
-
- @Override
- kin.base.xdr.Operation.OperationBody toOperationBody() {
- SetOptionsOp op = new SetOptionsOp();
- if (inflationDestination != null) {
- AccountID inflationDestination = new AccountID();
- inflationDestination.setAccountID(this.inflationDestination.getXdrPublicKey());
- op.setInflationDest(inflationDestination);
- }
- if (clearFlags != null) {
- Uint32 clearFlags = new Uint32();
- clearFlags.setUint32(this.clearFlags);
- op.setClearFlags(clearFlags);
- }
- if (setFlags != null) {
- Uint32 setFlags = new Uint32();
- setFlags.setUint32(this.setFlags);
- op.setSetFlags(setFlags);
- }
- if (masterKeyWeight != null) {
- Uint32 uint32 = new Uint32();
- uint32.setUint32(masterKeyWeight);
- op.setMasterWeight(uint32);
- }
- if (lowThreshold != null) {
- Uint32 uint32 = new Uint32();
- uint32.setUint32(lowThreshold);
- op.setLowThreshold(uint32);
- }
- if (mediumThreshold != null) {
- Uint32 uint32 = new Uint32();
- uint32.setUint32(mediumThreshold);
- op.setMedThreshold(uint32);
- }
- if (highThreshold != null) {
- Uint32 uint32 = new Uint32();
- uint32.setUint32(highThreshold);
- op.setHighThreshold(uint32);
- }
- if (homeDomain != null) {
- String32 homeDomain = new String32();
- homeDomain.setString32(this.homeDomain);
- op.setHomeDomain(homeDomain);
- }
- if (signer != null) {
- kin.base.xdr.Signer signer = new kin.base.xdr.Signer();
- Uint32 weight = new Uint32();
- weight.setUint32(signerWeight & 0xFF);
- signer.setKey(this.signer);
- signer.setWeight(weight);
- op.setSigner(signer);
- }
-
- kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
- body.setDiscriminant(OperationType.SET_OPTIONS);
- body.setSetOptionsOp(op);
- return body;
- }
+ private final KeyPair inflationDestination;
+ private final Integer clearFlags;
+ private final Integer setFlags;
+ private final Integer masterKeyWeight;
+ private final Integer lowThreshold;
+ private final Integer mediumThreshold;
+ private final Integer highThreshold;
+ private final String homeDomain;
+ private final SignerKey signer;
+ private final Integer signerWeight;
- /**
- * Builds SetOptions operation.
- * @see SetOptionsOperation
- */
- public static class Builder {
- private KeyPair inflationDestination;
- private Integer clearFlags;
- private Integer setFlags;
- private Integer masterKeyWeight;
- private Integer lowThreshold;
- private Integer mediumThreshold;
- private Integer highThreshold;
- private String homeDomain;
- private SignerKey signer;
- private Integer signerWeight;
- private KeyPair sourceAccount;
-
- Builder(SetOptionsOp op) {
- if (op.getInflationDest() != null) {
- inflationDestination = KeyPair.fromXdrPublicKey(
- op.getInflationDest().getAccountID());
- }
- if (op.getClearFlags() != null) {
- clearFlags = op.getClearFlags().getUint32();
- }
- if (op.getSetFlags() != null) {
- setFlags = op.getSetFlags().getUint32();
- }
- if (op.getMasterWeight() != null) {
- masterKeyWeight = op.getMasterWeight().getUint32().intValue();
- }
- if (op.getLowThreshold() != null) {
- lowThreshold = op.getLowThreshold().getUint32().intValue();
- }
- if (op.getMedThreshold() != null) {
- mediumThreshold = op.getMedThreshold().getUint32().intValue();
- }
- if (op.getHighThreshold() != null) {
- highThreshold = op.getHighThreshold().getUint32().intValue();
- }
- if (op.getHomeDomain() != null) {
- homeDomain = op.getHomeDomain().getString32();
- }
- if (op.getSigner() != null) {
- signer = op.getSigner().getKey();
- signerWeight = op.getSigner().getWeight().getUint32().intValue() & 0xFF;
- }
+ private SetOptionsOperation(KeyPair inflationDestination, Integer clearFlags, Integer setFlags,
+ Integer masterKeyWeight, Integer lowThreshold, Integer mediumThreshold,
+ Integer highThreshold, String homeDomain, SignerKey signer, Integer signerWeight) {
+ this.inflationDestination = inflationDestination;
+ this.clearFlags = clearFlags;
+ this.setFlags = setFlags;
+ this.masterKeyWeight = masterKeyWeight;
+ this.lowThreshold = lowThreshold;
+ this.mediumThreshold = mediumThreshold;
+ this.highThreshold = highThreshold;
+ this.homeDomain = homeDomain;
+ this.signer = signer;
+ this.signerWeight = signerWeight;
}
/**
- * Creates a new SetOptionsOperation builder.
- */
- public Builder() {}
-
- /**
- * Sets the inflation destination for the account.
- * @param inflationDestination The inflation destination account.
- * @return Builder object so you can chain methods.
+ * Account of the inflation destination.
*/
- public Builder setInflationDestination(KeyPair inflationDestination) {
- this.inflationDestination = inflationDestination;
- return this;
+ public KeyPair getInflationDestination() {
+ return inflationDestination;
}
/**
- * Clears the given flags from the account.
- * @param clearFlags For details about the flags, please refer to the accounts doc.
- * @return Builder object so you can chain methods.
+ * Indicates which flags to clear. For details about the flags, please refer to the accounts doc.
+ * You can also use {@link AccountFlag} enum.
*/
- public Builder setClearFlags(int clearFlags) {
- this.clearFlags = clearFlags;
- return this;
+ public Integer getClearFlags() {
+ return clearFlags;
}
/**
- * Sets the given flags on the account.
- * @param setFlags For details about the flags, please refer to the accounts doc.
- * @return Builder object so you can chain methods.
+ * Indicates which flags to set. For details about the flags, please refer to the accounts doc.
+ * You can also use {@link AccountFlag} enum.
*/
- public Builder setSetFlags(int setFlags) {
- this.setFlags = setFlags;
- return this;
+ public Integer getSetFlags() {
+ return setFlags;
}
/**
* Weight of the master key.
- * @param masterKeyWeight Number between 0 and 255
- * @return Builder object so you can chain methods.
*/
- public Builder setMasterKeyWeight(int masterKeyWeight) {
- this.masterKeyWeight = masterKeyWeight;
- return this;
+ public Integer getMasterKeyWeight() {
+ return masterKeyWeight;
}
/**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold.
- * @param lowThreshold Number between 0 and 255
- * @return Builder object so you can chain methods.
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold.
*/
- public Builder setLowThreshold(int lowThreshold) {
- this.lowThreshold = lowThreshold;
- return this;
+ public Integer getLowThreshold() {
+ return lowThreshold;
}
/**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold.
- * @param mediumThreshold Number between 0 and 255
- * @return Builder object so you can chain methods.
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold.
*/
- public Builder setMediumThreshold(int mediumThreshold) {
- this.mediumThreshold = mediumThreshold;
- return this;
+ public Integer getMediumThreshold() {
+ return mediumThreshold;
}
/**
- * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold.
- * @param highThreshold Number between 0 and 255
- * @return Builder object so you can chain methods.
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold.
*/
- public Builder setHighThreshold(int highThreshold) {
- this.highThreshold = highThreshold;
- return this;
+ public Integer getHighThreshold() {
+ return highThreshold;
}
/**
- * Sets the account's home domain address used in Federation.
- * @param homeDomain A string of the address which can be up to 32 characters.
- * @return Builder object so you can chain methods.
+ * The home domain of an account.
*/
- public Builder setHomeDomain(String homeDomain) {
- if (homeDomain.length() > 32) {
- throw new IllegalArgumentException("Home domain must be <= 32 characters");
- }
- this.homeDomain = homeDomain;
- return this;
+ public String getHomeDomain() {
+ return homeDomain;
}
/**
- * Add, update, or remove a signer from the account. Signer is deleted if the weight = 0;
- * @param signer The signer key. Use {@link Signer} helper to create this object.
- * @param weight The weight to attach to the signer (0-255).
- * @return Builder object so you can chain methods.
+ * Additional signer added/removed in this operation.
*/
- public Builder setSigner(SignerKey signer, Integer weight) {
- checkNotNull(signer, "signer cannot be null");
- checkNotNull(weight, "weight cannot be null");
- this.signer = signer;
- signerWeight = weight & 0xFF;
- return this;
+ public SignerKey getSigner() {
+ return signer;
}
/**
- * Sets the source account for this operation.
- * @param sourceAccount The operation's source account.
- * @return Builder object so you can chain methods.
+ * Additional signer weight. The signer is deleted if the weight is 0.
*/
- public Builder setSourceAccount(KeyPair sourceAccount) {
- this.sourceAccount = sourceAccount;
- return this;
+ public Integer getSignerWeight() {
+ return signerWeight;
+ }
+
+ @Override
+ kin.base.xdr.Operation.OperationBody toOperationBody() {
+ SetOptionsOp op = new SetOptionsOp();
+ if (inflationDestination != null) {
+ AccountID inflationDestination = new AccountID();
+ inflationDestination.setAccountID(this.inflationDestination.getXdrPublicKey());
+ op.setInflationDest(inflationDestination);
+ }
+ if (clearFlags != null) {
+ Uint32 clearFlags = new Uint32();
+ clearFlags.setUint32(this.clearFlags);
+ op.setClearFlags(clearFlags);
+ }
+ if (setFlags != null) {
+ Uint32 setFlags = new Uint32();
+ setFlags.setUint32(this.setFlags);
+ op.setSetFlags(setFlags);
+ }
+ if (masterKeyWeight != null) {
+ Uint32 uint32 = new Uint32();
+ uint32.setUint32(masterKeyWeight);
+ op.setMasterWeight(uint32);
+ }
+ if (lowThreshold != null) {
+ Uint32 uint32 = new Uint32();
+ uint32.setUint32(lowThreshold);
+ op.setLowThreshold(uint32);
+ }
+ if (mediumThreshold != null) {
+ Uint32 uint32 = new Uint32();
+ uint32.setUint32(mediumThreshold);
+ op.setMedThreshold(uint32);
+ }
+ if (highThreshold != null) {
+ Uint32 uint32 = new Uint32();
+ uint32.setUint32(highThreshold);
+ op.setHighThreshold(uint32);
+ }
+ if (homeDomain != null) {
+ String32 homeDomain = new String32();
+ homeDomain.setString32(this.homeDomain);
+ op.setHomeDomain(homeDomain);
+ }
+ if (signer != null) {
+ kin.base.xdr.Signer signer = new kin.base.xdr.Signer();
+ Uint32 weight = new Uint32();
+ weight.setUint32(signerWeight & 0xFF);
+ signer.setKey(this.signer);
+ signer.setWeight(weight);
+ op.setSigner(signer);
+ }
+
+ kin.base.xdr.Operation.OperationBody body = new kin.base.xdr.Operation.OperationBody();
+ body.setDiscriminant(OperationType.SET_OPTIONS);
+ body.setSetOptionsOp(op);
+ return body;
}
/**
- * Builds an operation
+ * Builds SetOptions operation.
+ *
+ * @see SetOptionsOperation
*/
- public SetOptionsOperation build() {
- SetOptionsOperation operation = new SetOptionsOperation(inflationDestination, clearFlags,
- setFlags, masterKeyWeight, lowThreshold, mediumThreshold, highThreshold,
- homeDomain, signer, signerWeight);
- if (sourceAccount != null) {
- operation.setSourceAccount(sourceAccount);
- }
- return operation;
+ public static class Builder {
+ private KeyPair inflationDestination;
+ private Integer clearFlags;
+ private Integer setFlags;
+ private Integer masterKeyWeight;
+ private Integer lowThreshold;
+ private Integer mediumThreshold;
+ private Integer highThreshold;
+ private String homeDomain;
+ private SignerKey signer;
+ private Integer signerWeight;
+ private KeyPair sourceAccount;
+
+ Builder(SetOptionsOp op) {
+ if (op.getInflationDest() != null) {
+ inflationDestination = KeyPair.fromXdrPublicKey(
+ op.getInflationDest().getAccountID());
+ }
+ if (op.getClearFlags() != null) {
+ clearFlags = op.getClearFlags().getUint32();
+ }
+ if (op.getSetFlags() != null) {
+ setFlags = op.getSetFlags().getUint32();
+ }
+ if (op.getMasterWeight() != null) {
+ masterKeyWeight = op.getMasterWeight().getUint32().intValue();
+ }
+ if (op.getLowThreshold() != null) {
+ lowThreshold = op.getLowThreshold().getUint32().intValue();
+ }
+ if (op.getMedThreshold() != null) {
+ mediumThreshold = op.getMedThreshold().getUint32().intValue();
+ }
+ if (op.getHighThreshold() != null) {
+ highThreshold = op.getHighThreshold().getUint32().intValue();
+ }
+ if (op.getHomeDomain() != null) {
+ homeDomain = op.getHomeDomain().getString32();
+ }
+ if (op.getSigner() != null) {
+ signer = op.getSigner().getKey();
+ signerWeight = op.getSigner().getWeight().getUint32().intValue() & 0xFF;
+ }
+ }
+
+ /**
+ * Creates a new SetOptionsOperation builder.
+ */
+ public Builder() {
+ }
+
+ /**
+ * Sets the inflation destination for the account.
+ *
+ * @param inflationDestination The inflation destination account.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setInflationDestination(KeyPair inflationDestination) {
+ this.inflationDestination = inflationDestination;
+ return this;
+ }
+
+ /**
+ * Clears the given flags from the account.
+ *
+ * @param clearFlags For details about the flags, please refer to the accounts doc.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setClearFlags(int clearFlags) {
+ this.clearFlags = clearFlags;
+ return this;
+ }
+
+ /**
+ * Sets the given flags on the account.
+ *
+ * @param setFlags For details about the flags, please refer to the accounts doc.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setSetFlags(int setFlags) {
+ this.setFlags = setFlags;
+ return this;
+ }
+
+ /**
+ * Weight of the master key.
+ *
+ * @param masterKeyWeight Number between 0 and 255
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setMasterKeyWeight(int masterKeyWeight) {
+ this.masterKeyWeight = masterKeyWeight;
+ return this;
+ }
+
+ /**
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a low threshold.
+ *
+ * @param lowThreshold Number between 0 and 255
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setLowThreshold(int lowThreshold) {
+ this.lowThreshold = lowThreshold;
+ return this;
+ }
+
+ /**
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a medium threshold.
+ *
+ * @param mediumThreshold Number between 0 and 255
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setMediumThreshold(int mediumThreshold) {
+ this.mediumThreshold = mediumThreshold;
+ return this;
+ }
+
+ /**
+ * A number from 0-255 representing the threshold this account sets on all operations it performs that have a high threshold.
+ *
+ * @param highThreshold Number between 0 and 255
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setHighThreshold(int highThreshold) {
+ this.highThreshold = highThreshold;
+ return this;
+ }
+
+ /**
+ * Sets the account's home domain address used in Federation.
+ *
+ * @param homeDomain A string of the address which can be up to 32 characters.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setHomeDomain(String homeDomain) {
+ if (homeDomain.length() > 32) {
+ throw new IllegalArgumentException("Home domain must be <= 32 characters");
+ }
+ this.homeDomain = homeDomain;
+ return this;
+ }
+
+ /**
+ * Add, update, or remove a signer from the account. Signer is deleted if the weight = 0;
+ *
+ * @param signer The signer key. Use {@link Signer} helper to create this object.
+ * @param weight The weight to attach to the signer (0-255).
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setSigner(SignerKey signer, Integer weight) {
+ checkNotNull(signer, "signer cannot be null");
+ checkNotNull(weight, "weight cannot be null");
+ this.signer = signer;
+ signerWeight = weight & 0xFF;
+ return this;
+ }
+
+ /**
+ * Sets the source account for this operation.
+ *
+ * @param sourceAccount The operation's source account.
+ * @return Builder object so you can chain methods.
+ */
+ public Builder setSourceAccount(KeyPair sourceAccount) {
+ this.sourceAccount = sourceAccount;
+ return this;
+ }
+
+ /**
+ * Builds an operation
+ */
+ public SetOptionsOperation build() {
+ SetOptionsOperation operation = new SetOptionsOperation(inflationDestination, clearFlags,
+ setFlags, masterKeyWeight, lowThreshold, mediumThreshold, highThreshold,
+ homeDomain, signer, signerWeight);
+ if (sourceAccount != null) {
+ operation.setSourceAccount(sourceAccount);
+ }
+ return operation;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Signer.java b/kin-sdk/kin-base/src/main/java/kin/base/Signer.java
index f2570304..fee54d2d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Signer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Signer.java
@@ -1,11 +1,11 @@
package kin.base;
-import static kin.base.Util.checkNotNull;
-
import kin.base.xdr.SignerKey;
import kin.base.xdr.SignerKeyType;
import kin.base.xdr.Uint256;
+import static kin.base.Util.checkNotNull;
+
/**
* Signer is a helper class that creates {@link kin.base.xdr.SignerKey} objects.
*/
@@ -13,6 +13,7 @@ public class Signer {
/**
* Create ed25519PublicKey {@link kin.base.xdr.SignerKey} from
* a {@link KeyPair}
+ *
* @param keyPair
* @return kin.base.xdr.SignerKey
*/
@@ -24,6 +25,7 @@ public static SignerKey ed25519PublicKey(KeyPair keyPair) {
/**
* Create sha256Hash {@link kin.base.xdr.SignerKey} from
* a sha256 hash of a preimage.
+ *
* @param hash
* @return kin.base.xdr.SignerKey
*/
@@ -41,6 +43,7 @@ public static SignerKey sha256Hash(byte[] hash) {
/**
* Create preAuthTx {@link kin.base.xdr.SignerKey} from
* a {@link kin.base.xdr.Transaction} hash.
+ *
* @param tx
* @return kin.base.xdr.SignerKey
*/
@@ -58,6 +61,7 @@ public static SignerKey preAuthTx(Transaction tx) {
/**
* Create preAuthTx {@link kin.base.xdr.SignerKey} from
* a transaction hash.
+ *
* @param hash
* @return kin.base.xdr.SignerKey
*/
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java b/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
index 6967b1b9..625c7926 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/StrKey.java
@@ -3,18 +3,21 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
+
import kin.base.codec.Base32;
class StrKey {
public enum VersionByte {
- ACCOUNT_ID((byte)(6 << 3)), // G
- SEED((byte)(18 << 3)), // S
- PRE_AUTH_TX((byte)(19 << 3)), // T
- SHA256_HASH((byte)(23 << 3)); // X
+ ACCOUNT_ID((byte) (6 << 3)), // G
+ SEED((byte) (18 << 3)), // S
+ PRE_AUTH_TX((byte) (19 << 3)), // T
+ SHA256_HASH((byte) (23 << 3)); // X
private final byte value;
+
VersionByte(byte value) {
this.value = value;
}
+
public int getValue() {
return value;
}
@@ -96,9 +99,9 @@ protected static byte[] decodeCheck(VersionByte versionByte, char[] encoded) {
Base32 base32Codec = new Base32();
byte[] decoded = base32Codec.decode(bytes);
byte decodedVersionByte = decoded[0];
- byte[] payload = Arrays.copyOfRange(decoded, 0, decoded.length-2);
- byte[] data = Arrays.copyOfRange(payload, 1, payload.length);
- byte[] checksum = Arrays.copyOfRange(decoded, decoded.length-2, decoded.length);
+ byte[] payload = Arrays.copyOfRange(decoded, 0, decoded.length - 2);
+ byte[] data = Arrays.copyOfRange(payload, 1, payload.length);
+ byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 2, decoded.length);
if (decodedVersionByte != versionByte.getValue()) {
throw new FormatException("Version byte is invalid");
@@ -141,8 +144,8 @@ protected static byte[] calculateChecksum(byte[] bytes) {
}
// little-endian
- return new byte[] {
- (byte)crc,
- (byte)(crc >>> 8)};
+ return new byte[]{
+ (byte) crc,
+ (byte) (crc >>> 8)};
}
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java b/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
index f324b6fb..ac9e129a 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/TimeBounds.java
@@ -4,63 +4,64 @@
/**
*
TimeBounds represents the time interval that a transaction is valid.
+ *
* @see Transaction
*/
final public class TimeBounds {
- final private long mMinTime;
- final private long mMaxTime;
+ final private long mMinTime;
+ final private long mMaxTime;
- /**
- * @param minTime 64bit Unix timestamp
- * @param maxTime 64bit Unix timestamp
- */
- public TimeBounds(long minTime, long maxTime) {
- if(minTime >= maxTime) {
- throw new IllegalArgumentException("minTime must be >= maxTime");
- }
+ /**
+ * @param minTime 64bit Unix timestamp
+ * @param maxTime 64bit Unix timestamp
+ */
+ public TimeBounds(long minTime, long maxTime) {
+ if (minTime >= maxTime) {
+ throw new IllegalArgumentException("minTime must be >= maxTime");
+ }
- mMinTime = minTime;
- mMaxTime = maxTime;
- }
+ mMinTime = minTime;
+ mMaxTime = maxTime;
+ }
- public long getMinTime() {
- return mMinTime;
- }
+ public long getMinTime() {
+ return mMinTime;
+ }
- public long getMaxTime() {
- return mMaxTime;
- }
+ public long getMaxTime() {
+ return mMaxTime;
+ }
- public static TimeBounds fromXdr(kin.base.xdr.TimeBounds timeBounds) {
- if (timeBounds == null) {
- return null;
- }
+ public static TimeBounds fromXdr(kin.base.xdr.TimeBounds timeBounds) {
+ if (timeBounds == null) {
+ return null;
+ }
- return new TimeBounds(
- timeBounds.getMinTime().getUint64(),
- timeBounds.getMaxTime().getUint64()
- );
- }
+ return new TimeBounds(
+ timeBounds.getMinTime().getUint64(),
+ timeBounds.getMaxTime().getUint64()
+ );
+ }
- public kin.base.xdr.TimeBounds toXdr() {
- kin.base.xdr.TimeBounds timeBounds = new kin.base.xdr.TimeBounds();
- Uint64 minTime = new Uint64();
- Uint64 maxTime = new Uint64();
- minTime.setUint64(mMinTime);
- maxTime.setUint64(mMaxTime);
- timeBounds.setMinTime(minTime);
- timeBounds.setMaxTime(maxTime);
- return timeBounds;
- }
+ public kin.base.xdr.TimeBounds toXdr() {
+ kin.base.xdr.TimeBounds timeBounds = new kin.base.xdr.TimeBounds();
+ Uint64 minTime = new Uint64();
+ Uint64 maxTime = new Uint64();
+ minTime.setUint64(mMinTime);
+ maxTime.setUint64(mMaxTime);
+ timeBounds.setMinTime(minTime);
+ timeBounds.setMaxTime(maxTime);
+ return timeBounds;
+ }
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
- TimeBounds that = (TimeBounds) o;
+ TimeBounds that = (TimeBounds) o;
- if (mMinTime != that.mMinTime) return false;
- return mMaxTime == that.mMaxTime;
- }
+ if (mMinTime != that.mMinTime) return false;
+ return mMaxTime == that.mMaxTime;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Transaction.java b/kin-sdk/kin-base/src/main/java/kin/base/Transaction.java
index 5ac24886..0862e6f4 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Transaction.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Transaction.java
@@ -1,8 +1,5 @@
package kin.base;
-import static kin.base.Util.checkArgument;
-import static kin.base.Util.checkNotNull;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -10,6 +7,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+
import kin.base.codec.Base64;
import kin.base.xdr.DecoratedSignature;
import kin.base.xdr.EnvelopeType;
@@ -17,12 +15,16 @@
import kin.base.xdr.TransactionEnvelope;
import kin.base.xdr.XdrDataOutputStream;
+import static kin.base.Util.checkArgument;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents Transaction in Stellar network.
*/
public class Transaction {
+<<<<<<< HEAD
private final int mFee;
private final KeyPair mSourceAccount;
private final long mSequenceNumber;
@@ -31,13 +33,14 @@ public class Transaction {
private final TimeBounds mTimeBounds;
private List mSignatures;
- Transaction(KeyPair sourceAccount, int fee, long sequenceNumber, Operation[] operations, Memo memo, TimeBounds timeBounds) {
+ Transaction(KeyPair sourceAccount, int feePerOperation, long sequenceNumber, Operation[] operations, Memo memo,
+ TimeBounds timeBounds) {
mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
mSequenceNumber = checkNotNull(sequenceNumber, "sequenceNumber cannot be null");
mOperations = checkNotNull(operations, "operations cannot be null");
checkArgument(operations.length > 0, "At least one operation required");
- mFee = operations.length * fee ;
+ mFee = operations.length * feePerOperation;
mSignatures = new ArrayList();
mMemo = memo != null ? memo : Memo.none();
mTimeBounds = timeBounds;
@@ -87,127 +90,94 @@ public byte[] hash() {
public byte[] signatureBase() {
if (Network.current() == null) {
throw new NoNetworkSelectedException();
+=======
+ private final int mFee;
+ private final KeyPair mSourceAccount;
+ private final long mSequenceNumber;
+ private final Operation[] mOperations;
+ private final Memo mMemo;
+ private final TimeBounds mTimeBounds;
+ private List mSignatures;
+
+ Transaction(KeyPair sourceAccount, int fee, long sequenceNumber, Operation[] operations, Memo memo, TimeBounds timeBounds) {
+ mSourceAccount = checkNotNull(sourceAccount, "sourceAccount cannot be null");
+ mSequenceNumber = checkNotNull(sequenceNumber, "sequenceNumber cannot be null");
+ mOperations = checkNotNull(operations, "operations cannot be null");
+ checkArgument(operations.length > 0, "At least one operation required");
+
+ mFee = operations.length * fee;
+ mSignatures = new ArrayList();
+ mMemo = memo != null ? memo : Memo.none();
+ mTimeBounds = timeBounds;
+>>>>>>> master
}
- try {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- // Hashed NetworkID
- outputStream.write(Network.current().getNetworkId());
- // Envelope Type - 4 bytes
- outputStream.write(ByteBuffer.allocate(4).putInt(EnvelopeType.ENVELOPE_TYPE_TX.getValue()).array());
- // Transaction XDR bytes
- ByteArrayOutputStream txOutputStream = new ByteArrayOutputStream();
- XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(txOutputStream);
- kin.base.xdr.Transaction.encode(xdrOutputStream, this.toXdr());
- outputStream.write(txOutputStream.toByteArray());
-
- return outputStream.toByteArray();
- } catch (IOException exception) {
- return null;
+ /**
+ * Adds a new signature ed25519PublicKey to this transaction.
+ *
+ * @param signer {@link KeyPair} object representing a signer
+ */
+ public void sign(KeyPair signer) {
+ checkNotNull(signer, "signer cannot be null");
+ byte[] txHash = this.hash();
+ mSignatures.add(signer.signDecorated(txHash));
}
- }
-
- public KeyPair getSourceAccount() {
- return mSourceAccount;
- }
-
- public long getSequenceNumber() {
- return mSequenceNumber;
- }
-
- public List getSignatures() {
- return mSignatures;
- }
- public Memo getMemo() {
- return mMemo;
- }
+ /**
+ * Adds a new sha256Hash signature to this transaction by revealing preimage.
+ *
+ * @param preimage the sha256 hash of preimage should be equal to signer hash
+ */
+ public void sign(byte[] preimage) {
+ checkNotNull(preimage, "preimage cannot be null");
+ kin.base.xdr.Signature signature = new kin.base.xdr.Signature();
+ signature.setSignature(preimage);
- public Operation[] getOperations() {
- return mOperations;
- }
+ byte[] hash = Util.hash(preimage);
+ byte[] signatureHintBytes = Arrays.copyOfRange(hash, hash.length - 4, hash.length);
+ SignatureHint signatureHint = new SignatureHint();
+ signatureHint.setSignatureHint(signatureHintBytes);
- /**
- * @return TimeBounds, or null (representing no time restrictions)
- */
- public TimeBounds getTimeBounds() {
- return mTimeBounds;
- }
+ DecoratedSignature decoratedSignature = new DecoratedSignature();
+ decoratedSignature.setHint(signatureHint);
+ decoratedSignature.setSignature(signature);
- /**
- * Returns fee paid for transaction in stroops (1 stroop = 0.0000001 XLM).
- */
- public int getFee() {
- return mFee;
- }
-
- /**
- * Generates Transaction XDR object.
- */
- public kin.base.xdr.Transaction toXdr() {
- // fee
- kin.base.xdr.Uint32 fee = new kin.base.xdr.Uint32();
- fee.setUint32(mFee);
- // sequenceNumber
- kin.base.xdr.Uint64 sequenceNumberUint = new kin.base.xdr.Uint64();
- sequenceNumberUint.setUint64(mSequenceNumber);
- kin.base.xdr.SequenceNumber sequenceNumber = new kin.base.xdr.SequenceNumber();
- sequenceNumber.setSequenceNumber(sequenceNumberUint);
- // sourceAccount
- kin.base.xdr.AccountID sourceAccount = new kin.base.xdr.AccountID();
- sourceAccount.setAccountID(mSourceAccount.getXdrPublicKey());
- // operations
- kin.base.xdr.Operation[] operations = new kin.base.xdr.Operation[mOperations.length];
- for (int i = 0; i < mOperations.length; i++) {
- operations[i] = mOperations[i].toXdr();
+ mSignatures.add(decoratedSignature);
}
- // ext
- kin.base.xdr.Transaction.TransactionExt ext = new kin.base.xdr.Transaction.TransactionExt();
- ext.setDiscriminant(0);
-
- kin.base.xdr.Transaction transaction = new kin.base.xdr.Transaction();
- transaction.setFee(fee);
- transaction.setSeqNum(sequenceNumber);
- transaction.setSourceAccount(sourceAccount);
- transaction.setOperations(operations);
- transaction.setMemo(mMemo.toXdr());
- transaction.setTimeBounds(mTimeBounds == null ? null : mTimeBounds.toXdr());
- transaction.setExt(ext);
- return transaction;
- }
- /**
- * Generates TransactionEnvelope XDR object. Transaction need to have at least one signature.
- */
- public kin.base.xdr.TransactionEnvelope toEnvelopeXdr() {
- if (mSignatures.size() == 0) {
- throw new NotEnoughSignaturesException("Transaction must be signed by at least one signer. Use transaction.sign().");
+ /**
+ * Returns transaction hash.
+ */
+ public byte[] hash() {
+ return Util.hash(this.signatureBase());
}
- kin.base.xdr.TransactionEnvelope xdr = new kin.base.xdr.TransactionEnvelope();
- kin.base.xdr.Transaction transaction = this.toXdr();
- xdr.setTx(transaction);
-
- DecoratedSignature[] signatures = new DecoratedSignature[mSignatures.size()];
- signatures = mSignatures.toArray(signatures);
- xdr.setSignatures(signatures);
- return xdr;
- }
-
- /**
- * Returns base64-encoded TransactionEnvelope XDR object. Transaction need to have at least one signature.
- */
- public String toEnvelopeXdrBase64() {
- try {
- kin.base.xdr.TransactionEnvelope envelope = this.toEnvelopeXdr();
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
- kin.base.xdr.TransactionEnvelope.encode(xdrOutputStream, envelope);
- Base64 base64Codec = new Base64();
- return base64Codec.encodeAsString(outputStream.toByteArray());
- } catch (IOException e) {
- throw new AssertionError(e);
+ /**
+ * Returns signature base.
+ */
+ public byte[] signatureBase() {
+ if (Network.current() == null) {
+ throw new NoNetworkSelectedException();
+ }
+
+ try {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ // Hashed NetworkID
+ outputStream.write(Network.current().getNetworkId());
+ // Envelope Type - 4 bytes
+ outputStream.write(ByteBuffer.allocate(4).putInt(EnvelopeType.ENVELOPE_TYPE_TX.getValue()).array());
+ // Transaction XDR bytes
+ ByteArrayOutputStream txOutputStream = new ByteArrayOutputStream();
+ XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(txOutputStream);
+ kin.base.xdr.Transaction.encode(xdrOutputStream, this.toXdr());
+ outputStream.write(txOutputStream.toByteArray());
+
+ return outputStream.toByteArray();
+ } catch (IOException exception) {
+ return null;
+ }
}
+<<<<<<< HEAD
}
/**
@@ -228,7 +198,14 @@ public static Transaction fromEnvelopeXdr(String envelope) throws IOException {
*/
public static Transaction fromEnvelopeXdr(TransactionEnvelope envelope) {
kin.base.xdr.Transaction tx = envelope.getTx();
- int mFee = tx.getFee().getUint32();
+ // Although currently there couldn't be a transaction with no operations we still check it.
+ int feePerOperation = tx.getFee().getUint32();
+ if (tx.getOperations().length > 1) {
+ // Because the fee was already multiplied by number of operation then divide by it because when reCreate this
+ // transaction then we will multiple it again.
+ feePerOperation = feePerOperation / tx.getOperations().length;
+ }
+
KeyPair mSourceAccount = KeyPair.fromXdrPublicKey(tx.getSourceAccount().getAccountID());
Long mSequenceNumber = tx.getSeqNum().getSequenceNumber().getUint64();
Memo mMemo = Memo.fromXdr(tx.getMemo());
@@ -239,102 +216,245 @@ public static Transaction fromEnvelopeXdr(TransactionEnvelope envelope) {
mOperations[i] = Operation.fromXdr(tx.getOperations()[i]);
}
- Transaction transaction = new Transaction(mSourceAccount, mFee, mSequenceNumber, mOperations, mMemo, mTimeBounds);
+ Transaction transaction = new Transaction(mSourceAccount, feePerOperation, mSequenceNumber, mOperations, mMemo,
+ mTimeBounds);
+=======
- for (DecoratedSignature signature : envelope.getSignatures()) {
- transaction.mSignatures.add(signature);
+ public KeyPair getSourceAccount() {
+ return mSourceAccount;
}
- return transaction;
- }
+ public long getSequenceNumber() {
+ return mSequenceNumber;
+ }
+>>>>>>> master
- /**
- * Builds a new Transaction object.
- */
- public static class Builder {
- private final TransactionBuilderAccount mSourceAccount;
- private int fee ;
- private Memo mMemo;
- private TimeBounds mTimeBounds;
- List mOperations;
+ public List getSignatures() {
+ return mSignatures;
+ }
+
+ public Memo getMemo() {
+ return mMemo;
+ }
+
+ public Operation[] getOperations() {
+ return mOperations;
+ }
/**
- * Construct a new transaction builder.
- * @param sourceAccount The source account for this transaction. This account is the account
- * who will use a sequence number. When build() is called, the account object's sequence number
- * will be incremented.
+ * @return TimeBounds, or null (representing no time restrictions)
*/
- public Builder(TransactionBuilderAccount sourceAccount) {
- checkNotNull(sourceAccount, "sourceAccount cannot be null");
- mSourceAccount = sourceAccount;
- mOperations = Collections.synchronizedList(new ArrayList());
+ public TimeBounds getTimeBounds() {
+ return mTimeBounds;
}
- public int getOperationsCount() {
- return mOperations.size();
+ /**
+ * Returns fee paid for transaction in stroops (1 stroop = 0.0000001 XLM).
+ */
+ public int getFee() {
+ return mFee;
}
/**
- * Adds a new operation to this transaction.
- * @param operation
- * @return Builder object so you can chain methods.
- * @see Operation
+ * Generates Transaction XDR object.
*/
- public Builder addOperation(Operation operation) {
- checkNotNull(operation, "operation cannot be null");
- mOperations.add(operation);
- return this;
+ public kin.base.xdr.Transaction toXdr() {
+ // fee
+ kin.base.xdr.Uint32 fee = new kin.base.xdr.Uint32();
+ fee.setUint32(mFee);
+ // sequenceNumber
+ kin.base.xdr.Uint64 sequenceNumberUint = new kin.base.xdr.Uint64();
+ sequenceNumberUint.setUint64(mSequenceNumber);
+ kin.base.xdr.SequenceNumber sequenceNumber = new kin.base.xdr.SequenceNumber();
+ sequenceNumber.setSequenceNumber(sequenceNumberUint);
+ // sourceAccount
+ kin.base.xdr.AccountID sourceAccount = new kin.base.xdr.AccountID();
+ sourceAccount.setAccountID(mSourceAccount.getXdrPublicKey());
+ // operations
+ kin.base.xdr.Operation[] operations = new kin.base.xdr.Operation[mOperations.length];
+ for (int i = 0; i < mOperations.length; i++) {
+ operations[i] = mOperations[i].toXdr();
+ }
+ // ext
+ kin.base.xdr.Transaction.TransactionExt ext = new kin.base.xdr.Transaction.TransactionExt();
+ ext.setDiscriminant(0);
+
+ kin.base.xdr.Transaction transaction = new kin.base.xdr.Transaction();
+ transaction.setFee(fee);
+ transaction.setSeqNum(sequenceNumber);
+ transaction.setSourceAccount(sourceAccount);
+ transaction.setOperations(operations);
+ transaction.setMemo(mMemo.toXdr());
+ transaction.setTimeBounds(mTimeBounds == null ? null : mTimeBounds.toXdr());
+ transaction.setExt(ext);
+ return transaction;
}
/**
- * @param fee this transaction fee
- * @return Builder object so you can chain methods.
+ * Generates TransactionEnvelope XDR object. Transaction need to have at least one signature.
*/
- public Builder addFee(int fee) {
- this.fee = fee;
- return this;
+ public kin.base.xdr.TransactionEnvelope toEnvelopeXdr() {
+ if (mSignatures.size() == 0) {
+ throw new NotEnoughSignaturesException("Transaction must be signed by at least one signer. Use transaction.sign().");
+ }
+
+ kin.base.xdr.TransactionEnvelope xdr = new kin.base.xdr.TransactionEnvelope();
+ kin.base.xdr.Transaction transaction = this.toXdr();
+ xdr.setTx(transaction);
+
+ DecoratedSignature[] signatures = new DecoratedSignature[mSignatures.size()];
+ signatures = mSignatures.toArray(signatures);
+ xdr.setSignatures(signatures);
+ return xdr;
}
/**
- * Adds a memo to this transaction.
- * @param memo
- * @return Builder object so you can chain methods.
- * @see Memo
+ * Returns base64-encoded TransactionEnvelope XDR object. Transaction need to have at least one signature.
*/
- public Builder addMemo(Memo memo) {
- if (mMemo != null) {
- throw new RuntimeException("Memo has been already added.");
- }
- checkNotNull(memo, "memo cannot be null");
- mMemo = memo;
- return this;
+ public String toEnvelopeXdrBase64() {
+ try {
+ kin.base.xdr.TransactionEnvelope envelope = this.toEnvelopeXdr();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(outputStream);
+ kin.base.xdr.TransactionEnvelope.encode(xdrOutputStream, envelope);
+ Base64 base64Codec = new Base64();
+ return base64Codec.encodeAsString(outputStream.toByteArray());
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
}
-
+
/**
- * Adds a time-bounds to this transaction.
- * @param timeBounds
- * @return Builder object so you can chain methods.
- * @see TimeBounds
+ * Creates a Transaction instance from previously build TransactionEnvelope
+ *
+ * @param envelope Base-64 encoded TransactionEnvelope
+ * @return
+ * @throws IOException
*/
- public Builder addTimeBounds(TimeBounds timeBounds) {
- if (mTimeBounds != null) {
- throw new RuntimeException("TimeBounds has been already added.");
- }
- checkNotNull(timeBounds, "timeBounds cannot be null");
- mTimeBounds = timeBounds;
- return this;
+ public static Transaction fromEnvelopeXdr(String envelope) throws IOException {
+ TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(Util.createXdrDataInputStream(envelope));
+ return fromEnvelopeXdr(transactionEnvelope);
}
/**
- * Builds a transaction. It will increment sequence number of the source account.
+ * Creates a Transaction instance from previously build TransactionEnvelope
+ *
+ * @param envelope Base-64 encoded TransactionEnvelope
+ * @return
*/
- public Transaction build() {
- Operation[] operations = new Operation[mOperations.size()];
- operations = mOperations.toArray(operations);
- Transaction transaction = new Transaction(mSourceAccount.getKeypair(), fee, mSourceAccount.getIncrementedSequenceNumber(), operations, mMemo, mTimeBounds);
- // Increment sequence number when there were no exceptions when creating a transaction
- mSourceAccount.incrementSequenceNumber();
- return transaction;
+ public static Transaction fromEnvelopeXdr(TransactionEnvelope envelope) {
+ kin.base.xdr.Transaction tx = envelope.getTx();
+ int mFee = tx.getFee().getUint32();
+ KeyPair mSourceAccount = KeyPair.fromXdrPublicKey(tx.getSourceAccount().getAccountID());
+ Long mSequenceNumber = tx.getSeqNum().getSequenceNumber().getUint64();
+ Memo mMemo = Memo.fromXdr(tx.getMemo());
+ TimeBounds mTimeBounds = TimeBounds.fromXdr(tx.getTimeBounds());
+
+ Operation[] mOperations = new Operation[tx.getOperations().length];
+ for (int i = 0; i < tx.getOperations().length; i++) {
+ mOperations[i] = Operation.fromXdr(tx.getOperations()[i]);
+ }
+
+ Transaction transaction = new Transaction(mSourceAccount, mFee, mSequenceNumber, mOperations, mMemo, mTimeBounds);
+
+ for (DecoratedSignature signature : envelope.getSignatures()) {
+ transaction.mSignatures.add(signature);
+ }
+
+ return transaction;
+ }
+
+ /**
+ * Builds a new Transaction object.
+ */
+ public static class Builder {
+ private final TransactionBuilderAccount mSourceAccount;
+ private int fee;
+ private Memo mMemo;
+ private TimeBounds mTimeBounds;
+ List mOperations;
+
+ /**
+ * Construct a new transaction builder.
+ *
+ * @param sourceAccount The source account for this transaction. This account is the account
+ * who will use a sequence number. When build() is called, the account object's sequence number
+ * will be incremented.
+ */
+ public Builder(TransactionBuilderAccount sourceAccount) {
+ checkNotNull(sourceAccount, "sourceAccount cannot be null");
+ mSourceAccount = sourceAccount;
+ mOperations = Collections.synchronizedList(new ArrayList());
+ }
+
+ public int getOperationsCount() {
+ return mOperations.size();
+ }
+
+ /**
+ * Adds a new operation to this transaction.
+ *
+ * @param operation
+ * @return Builder object so you can chain methods.
+ * @see Operation
+ */
+ public Builder addOperation(Operation operation) {
+ checkNotNull(operation, "operation cannot be null");
+ mOperations.add(operation);
+ return this;
+ }
+
+ /**
+ * @param fee this transaction fee
+ * @return Builder object so you can chain methods.
+ */
+ public Builder addFee(int fee) {
+ this.fee = fee;
+ return this;
+ }
+
+ /**
+ * Adds a memo to this transaction.
+ *
+ * @param memo
+ * @return Builder object so you can chain methods.
+ * @see Memo
+ */
+ public Builder addMemo(Memo memo) {
+ if (mMemo != null) {
+ throw new RuntimeException("Memo has been already added.");
+ }
+ checkNotNull(memo, "memo cannot be null");
+ mMemo = memo;
+ return this;
+ }
+
+ /**
+ * Adds a time-bounds to this transaction.
+ *
+ * @param timeBounds
+ * @return Builder object so you can chain methods.
+ * @see TimeBounds
+ */
+ public Builder addTimeBounds(TimeBounds timeBounds) {
+ if (mTimeBounds != null) {
+ throw new RuntimeException("TimeBounds has been already added.");
+ }
+ checkNotNull(timeBounds, "timeBounds cannot be null");
+ mTimeBounds = timeBounds;
+ return this;
+ }
+
+ /**
+ * Builds a transaction. It will increment sequence number of the source account.
+ */
+ public Transaction build() {
+ Operation[] operations = new Operation[mOperations.size()];
+ operations = mOperations.toArray(operations);
+ Transaction transaction = new Transaction(mSourceAccount.getKeypair(), fee, mSourceAccount.getIncrementedSequenceNumber(), operations, mMemo, mTimeBounds);
+ // Increment sequence number when there were no exceptions when creating a transaction
+ mSourceAccount.incrementSequenceNumber();
+ return transaction;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/TransactionBuilderAccount.java b/kin-sdk/kin-base/src/main/java/kin/base/TransactionBuilderAccount.java
index 59c90c4c..5c2e8223 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/TransactionBuilderAccount.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/TransactionBuilderAccount.java
@@ -4,23 +4,23 @@
* Specifies interface for Account object used in {@link Transaction.Builder}
*/
public interface TransactionBuilderAccount {
- /**
- * Returns keypair associated with this Account
- */
- KeyPair getKeypair();
+ /**
+ * Returns keypair associated with this Account
+ */
+ KeyPair getKeypair();
- /**
- * Returns current sequence number ot this Account.
- */
- Long getSequenceNumber();
+ /**
+ * Returns current sequence number ot this Account.
+ */
+ Long getSequenceNumber();
- /**
- * Returns sequence number incremented by one, but does not increment internal counter.
- */
- Long getIncrementedSequenceNumber();
+ /**
+ * Returns sequence number incremented by one, but does not increment internal counter.
+ */
+ Long getIncrementedSequenceNumber();
- /**
- * Increments sequence number in this object by one.
- */
- void incrementSequenceNumber();
+ /**
+ * Increments sequence number in this object by one.
+ */
+ void incrementSequenceNumber();
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/TrustLineLedgerEntryChange.java b/kin-sdk/kin-base/src/main/java/kin/base/TrustLineLedgerEntryChange.java
index 12b35aab..19a65b45 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/TrustLineLedgerEntryChange.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/TrustLineLedgerEntryChange.java
@@ -5,38 +5,38 @@
public class TrustLineLedgerEntryChange extends LedgerEntryChange {
- private KeyPair accountID;
- private Asset asset;
- private String balance;
- private String limit;
- private Uint32 flags;
-
- TrustLineLedgerEntryChange() {
- }
-
- public KeyPair getAccount() {
- return this.accountID;
- }
-
- public Asset getAsset() {
- return this.asset;
- }
-
- public String getBalance() {
- return this.balance;
- }
-
- public String getLimit() {
- return this.limit;
- }
-
- public static TrustLineLedgerEntryChange fromXdr(kin.base.xdr.TrustLineEntry xdr) {
- TrustLineLedgerEntryChange entry = new TrustLineLedgerEntryChange();
- entry.accountID = KeyPair.fromXdrPublicKey(xdr.getAccountID().getAccountID());
- entry.asset = Asset.fromXdr(xdr.getAsset());
- entry.balance = Operation.fromXdrAmount(xdr.getBalance().getInt64());
- entry.limit = Operation.fromXdrAmount(xdr.getLimit().getInt64());
- return entry;
- }
+ private KeyPair accountID;
+ private Asset asset;
+ private String balance;
+ private String limit;
+ private Uint32 flags;
+
+ TrustLineLedgerEntryChange() {
+ }
+
+ public KeyPair getAccount() {
+ return this.accountID;
+ }
+
+ public Asset getAsset() {
+ return this.asset;
+ }
+
+ public String getBalance() {
+ return this.balance;
+ }
+
+ public String getLimit() {
+ return this.limit;
+ }
+
+ public static TrustLineLedgerEntryChange fromXdr(kin.base.xdr.TrustLineEntry xdr) {
+ TrustLineLedgerEntryChange entry = new TrustLineLedgerEntryChange();
+ entry.accountID = KeyPair.fromXdrPublicKey(xdr.getAccountID().getAccountID());
+ entry.asset = Asset.fromXdr(xdr.getAsset());
+ entry.balance = Operation.fromXdrAmount(xdr.getBalance().getInt64());
+ entry.limit = Operation.fromXdrAmount(xdr.getLimit().getInt64());
+ return entry;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/Util.java b/kin-sdk/kin-base/src/main/java/kin/base/Util.java
index 51803dfc..ab46a29f 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/Util.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/Util.java
@@ -6,95 +6,100 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
+
import kin.base.codec.Base64;
import kin.base.xdr.XdrDataInputStream;
public class Util {
- public static final String CHARSET_UTF8 = "UTF-8";
- static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
+ public static final String CHARSET_UTF8 = "UTF-8";
+ static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
- static String bytesToHex(byte[] bytes) {
- char[] hexChars = new char[bytes.length * 2];
- for ( int j = 0; j < bytes.length; j++ ) {
- int v = bytes[j] & 0xFF;
- hexChars[j * 2] = HEX_ARRAY[v >>> 4];
- hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
+ static String bytesToHex(byte[] bytes) {
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = HEX_ARRAY[v >>> 4];
+ hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
+ }
+ return new String(hexChars);
}
- return new String(hexChars);
- }
- static byte[] hexToBytes(String s) {
- int len = s.length();
- byte[] data = new byte[len / 2];
- for (int i = 0; i < len; i += 2) {
- data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
- + Character.digit(s.charAt(i+1), 16));
+ static byte[] hexToBytes(String s) {
+ int len = s.length();
+ byte[] data = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ + Character.digit(s.charAt(i + 1), 16));
+ }
+ return data;
}
- return data;
- }
- /**
- * Returns SHA-256 hash of data.
- * @param data
- */
- static byte[] hash(byte[] data) {
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- md.update(data);
- return md.digest();
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException("SHA-256 not implemented");
+ /**
+ * Returns SHA-256 hash of data.
+ *
+ * @param data
+ */
+ static byte[] hash(byte[] data) {
+ try {
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(data);
+ return md.digest();
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException("SHA-256 not implemented");
+ }
}
- }
- /**
- * Pads bytes array to length with zeros.
- * @param bytes
- * @param length
- */
- static byte[] paddedByteArray(byte[] bytes, int length) {
- byte[] finalBytes = new byte[length];
- Arrays.fill(finalBytes, (byte) 0);
- System.arraycopy(bytes, 0, finalBytes, 0, bytes.length);
- return finalBytes;
- }
+ /**
+ * Pads bytes array to length with zeros.
+ *
+ * @param bytes
+ * @param length
+ */
+ static byte[] paddedByteArray(byte[] bytes, int length) {
+ byte[] finalBytes = new byte[length];
+ Arrays.fill(finalBytes, (byte) 0);
+ System.arraycopy(bytes, 0, finalBytes, 0, bytes.length);
+ return finalBytes;
+ }
- /**
- * Pads string to length with zeros.
- * @param string
- * @param length
- */
- static byte[] paddedByteArray(String string, int length) {
- return Util.paddedByteArray(string.getBytes(), length);
- }
+ /**
+ * Pads string to length with zeros.
+ *
+ * @param string
+ * @param length
+ */
+ static byte[] paddedByteArray(String string, int length) {
+ return Util.paddedByteArray(string.getBytes(), length);
+ }
- /**
- * Remove zeros from the end of bytes array.
- * @param bytes
- */
- static String paddedByteArrayToString(byte[] bytes) {
- return new String(bytes).split("\0")[0];
- }
+ /**
+ * Remove zeros from the end of bytes array.
+ *
+ * @param bytes
+ */
+ static String paddedByteArrayToString(byte[] bytes) {
+ return new String(bytes).split("\0")[0];
+ }
- public static T checkNotNull(T obj, String msg) {
- if (obj == null) {
- throw new NullPointerException(msg);
- } else {
- return obj;
- }
- }
+ public static T checkNotNull(T obj, String msg) {
+ if (obj == null) {
+ throw new NullPointerException(msg);
+ } else {
+ return obj;
+ }
+ }
- public static void checkArgument(boolean expression, final Object errorMessage) {
- if (!expression) {
- throw new IllegalArgumentException(String.valueOf(errorMessage));
- }
- }
+ public static void checkArgument(boolean expression, final Object errorMessage) {
+ if (!expression) {
+ throw new IllegalArgumentException(String.valueOf(errorMessage));
+ }
+ }
- public static XdrDataInputStream createXdrDataInputStream(String envelopeXdr) throws UnsupportedEncodingException {
- Base64 base64 = new Base64();
- byte[] decoded = base64.decode(envelopeXdr.getBytes(CHARSET_UTF8));
- InputStream is = new ByteArrayInputStream(decoded);
- return new XdrDataInputStream(is);
- }
+ public static XdrDataInputStream createXdrDataInputStream(String envelopeXdr) throws UnsupportedEncodingException {
+ Base64 base64 = new Base64();
+ byte[] decoded = base64.decode(envelopeXdr.getBytes(CHARSET_UTF8));
+ InputStream is = new ByteArrayInputStream(decoded);
+ return new XdrDataInputStream(is);
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base32.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base32.java
index d774d6ef..068b44a3 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base32.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base32.java
@@ -53,10 +53,9 @@
* This class is not thread-safe. Each thread should use its own instance.
*
*
+ * @version $Revision$
* @see RFC 4648
- *
* @since 1.5
- * @version $Revision$
*/
public class Base32 extends BaseNCodec {
@@ -80,7 +79,6 @@ public class Base32 extends BaseNCodec {
* This array is a lookup table that translates Unicode characters drawn from the "Base32 Alphabet" (as specified in
* Table 3 of RFC 2045) into their 5-bit positive integer equivalents. Characters that are not in the Base32
* alphabet but fall within the bounds of the array are translated to -1.
- *
*/
private static final byte[] DECODE_TABLE = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
@@ -88,7 +86,7 @@ public class Base32 extends BaseNCodec {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 63, // 20-2f
-1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4f A-N
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4f A-N
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 50-5a O-Z
};
@@ -106,14 +104,13 @@ public class Base32 extends BaseNCodec {
* This array is a lookup table that translates Unicode characters drawn from the "Base32 |Hex Alphabet" (as specified in
* Table 3 of RFC 2045) into their 5-bit positive integer equivalents. Characters that are not in the Base32 Hex
* alphabet but fall within the bounds of the array are translated to -1.
- *
*/
private static final byte[] HEX_DECODE_TABLE = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 63, // 20-2f
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 40-4f A-N
25, 26, 27, 28, 29, 30, 31, 32, // 50-57 O-V
};
@@ -128,7 +125,9 @@ public class Base32 extends BaseNCodec {
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
};
- /** Mask used to extract 5 bits, used when encoding Base32 bytes */
+ /**
+ * Mask used to extract 5 bits, used when encoding Base32 bytes
+ */
private static final int MASK_5BITS = 0x1f;
// The static final fields above are used for the original static byte[] methods on Base32.
@@ -171,7 +170,6 @@ public class Base32 extends BaseNCodec {
*
* When encoding the line length is 0 (no chunking).
*
- *
*/
public Base32() {
this(false);
@@ -182,6 +180,7 @@ public Base32() {
*
* When encoding the line length is 0 (no chunking).
*
+ *
* @param useHex if true then use Base32 Hex alphabet
*/
public Base32(boolean useHex) {
@@ -194,9 +193,8 @@ public Base32(boolean useHex) {
* When encoding the line length is given in the constructor, the line separator is CRLF.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
*/
public Base32(int lineLength) {
this(lineLength, CHUNK_SEPARATOR);
@@ -211,13 +209,10 @@ public Base32(int lineLength) {
* Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @throws IllegalArgumentException
- * The provided lineSeparator included some Base32 characters. That's not going to work!
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @throws IllegalArgumentException The provided lineSeparator included some Base32 characters. That's not going to work!
*/
public Base32(int lineLength, byte[] lineSeparator) {
this(lineLength, lineSeparator, false);
@@ -232,21 +227,18 @@ public Base32(int lineLength, byte[] lineSeparator) {
* Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @param useHex if true, then use Base32 Hex alphabet, otherwise use Base32 alphabet
- * @throws IllegalArgumentException
- * The provided lineSeparator included some Base32 characters. That's not going to work!
- * Or the lineLength > 0 and lineSeparator is null.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 8).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @param useHex if true, then use Base32 Hex alphabet, otherwise use Base32 alphabet
+ * @throws IllegalArgumentException The provided lineSeparator included some Base32 characters. That's not going to work!
+ * Or the lineLength > 0 and lineSeparator is null.
*/
public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK,
lineLength,
lineSeparator == null ? 0 : lineSeparator.length);
- if (useHex){
+ if (useHex) {
this.encodeTable = HEX_ENCODE_TABLE;
this.decodeTable = HEX_DECODE_TABLE;
} else {
@@ -255,7 +247,7 @@ public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
}
if (lineLength > 0) {
if (lineSeparator == null) {
- throw new IllegalArgumentException("lineLength "+lineLength+" > 0, but lineSeparator is null");
+ throw new IllegalArgumentException("lineLength " + lineLength + " > 0, but lineSeparator is null");
}
// Must be done after initializing the tables
if (containsAlphabetOrPad(lineSeparator)) {
@@ -284,13 +276,9 @@ public Base32(int lineLength, byte[] lineSeparator, boolean useHex) {
* garbage-out philosophy: it will not check the provided data for validity.
*
*
- * @param in
- * byte[] array of ascii data to Base32 decode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
- *
+ * @param in byte[] array of ascii data to Base32 decode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) { // package protected for access from I/O streams
if (eof) {
@@ -310,7 +298,7 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
if (b >= 0 && b < this.decodeTable.length) {
int result = this.decodeTable[b];
if (result >= 0) {
- modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result; // collect decoded bytes
if (modulus == 0) { // we can output the 5 bytes
buffer[pos++] = (byte) ((bitWorkArea >> 32) & MASK_8BITS);
@@ -332,30 +320,30 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
// we ignore partial bytes, i.e. only multiples of 8 count
switch (modulus) {
- case 2 : // 10 bits, drop 2 and output one byte
+ case 2: // 10 bits, drop 2 and output one byte
buffer[pos++] = (byte) ((bitWorkArea >> 2) & MASK_8BITS);
break;
- case 3 : // 15 bits, drop 7 and output 1 byte
+ case 3: // 15 bits, drop 7 and output 1 byte
buffer[pos++] = (byte) ((bitWorkArea >> 7) & MASK_8BITS);
break;
- case 4 : // 20 bits = 2*8 + 4
+ case 4: // 20 bits = 2*8 + 4
bitWorkArea = bitWorkArea >> 4; // drop 4 bits
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 5 : // 25bits = 3*8 + 1
+ case 5: // 25bits = 3*8 + 1
bitWorkArea = bitWorkArea >> 1;
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 6 : // 30bits = 3*8 + 6
+ case 6: // 30bits = 3*8 + 6
bitWorkArea = bitWorkArea >> 6;
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 7 : // 35 = 4*8 +3
+ case 7: // 35 = 4*8 +3
bitWorkArea = bitWorkArea >> 3;
buffer[pos++] = (byte) ((bitWorkArea >> 24) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
@@ -373,12 +361,9 @@ void decode(byte[] in, int inPos, int inAvail) { // package protected for access
* remaining bytes (if not multiple of 5).
*
*
- * @param in
- * byte[] array of binary data to Base32 encode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of binary data to Base32 encode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) { // package protected for access from I/O streams
if (eof) {
@@ -394,9 +379,9 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
ensureBufferSize(encodeSize);
int savedPos = pos;
switch (modulus) { // % 5
- case 1 : // Only 1 octet; take top 5 bits then remainder
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 2) & MASK_5BITS]; // 5-3=2
+ case 1: // Only 1 octet; take top 5 bits then remainder
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 2) & MASK_5BITS]; // 5-3=2
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
@@ -405,61 +390,61 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
buffer[pos++] = PAD;
break;
- case 2 : // 2 octets = 16 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 6) & MASK_5BITS]; // 16-2*5 = 6
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 1) & MASK_5BITS]; // 16-3*5 = 1
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 4) & MASK_5BITS]; // 5-1 = 4
+ case 2: // 2 octets = 16 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 6) & MASK_5BITS]; // 16-2*5 = 6
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 1) & MASK_5BITS]; // 16-3*5 = 1
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 4) & MASK_5BITS]; // 5-1 = 4
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
break;
- case 3 : // 3 octets = 24 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 9) & MASK_5BITS]; // 24-3*5 = 9
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 4) & MASK_5BITS]; // 24-4*5 = 4
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 1) & MASK_5BITS]; // 5-4 = 1
+ case 3: // 3 octets = 24 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 9) & MASK_5BITS]; // 24-3*5 = 9
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 4) & MASK_5BITS]; // 24-4*5 = 4
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 1) & MASK_5BITS]; // 5-4 = 1
buffer[pos++] = PAD;
buffer[pos++] = PAD;
buffer[pos++] = PAD;
break;
- case 4 : // 4 octets = 32 bits to use
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 7) & MASK_5BITS]; // 32-5*5 = 7
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 2) & MASK_5BITS]; // 32-6*5 = 2
- buffer[pos++] = encodeTable[(int)(bitWorkArea << 3) & MASK_5BITS]; // 5-2 = 3
+ case 4: // 4 octets = 32 bits to use
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 7) & MASK_5BITS]; // 32-5*5 = 7
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 2) & MASK_5BITS]; // 32-6*5 = 2
+ buffer[pos++] = encodeTable[(int) (bitWorkArea << 3) & MASK_5BITS]; // 5-2 = 3
buffer[pos++] = PAD;
break;
}
currentLinePos += pos - savedPos; // keep track of current line position
// if currentPos == 0 we are at the start of a line, so don't add CRLF
- if (lineLength > 0 && currentLinePos > 0){ // add chunk separator if required
+ if (lineLength > 0 && currentLinePos > 0) { // add chunk separator if required
System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
pos += lineSeparator.length;
}
} else {
for (int i = 0; i < inAvail; i++) {
ensureBufferSize(encodeSize);
- modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
int b = in[inPos++];
if (b < 0) {
b += 256;
}
bitWorkArea = (bitWorkArea << 8) + b; // BITS_PER_BYTE
if (0 == modulus) { // we have enough bytes to create our output
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 35) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 30) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 25) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 20) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 15) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 10) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)(bitWorkArea >> 5) & MASK_5BITS];
- buffer[pos++] = encodeTable[(int)bitWorkArea & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 35) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 30) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 25) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 20) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 15) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 10) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) (bitWorkArea >> 5) & MASK_5BITS];
+ buffer[pos++] = encodeTable[(int) bitWorkArea & MASK_5BITS];
currentLinePos += BYTES_PER_ENCODED_BLOCK;
if (lineLength > 0 && lineLength <= currentLinePos) {
System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
@@ -474,8 +459,7 @@ void encode(byte[] in, int inPos, int inAvail) { // package protected for access
/**
* Returns whether or not the octet is in the Base32 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the Base32 alphabet false otherwise.
*/
public boolean isInAlphabet(byte octet) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
index 93e34ca0..c8acfc84 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Base64.java
@@ -59,10 +59,10 @@
* This class is not thread-safe. Each thread should use its own instance.
*
*
- * @see RFC 2045
* @author Apache Software Foundation
- * @since 1.0
* @version $Revision$
+ * @see RFC 2045
+ * @since 1.0
*/
public class Base64 extends BaseNCodec {
@@ -89,7 +89,7 @@ public class Base64 extends BaseNCodec {
/**
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
* equivalents as specified in Table 1 of RFC 2045.
- *
+ *
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
@@ -118,10 +118,10 @@ public class Base64 extends BaseNCodec {
* This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
* Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
* alphabet but fall within the bounds of the array are translated to -1.
- *
+ *
* Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
* URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
- *
+ *
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
@@ -138,7 +138,9 @@ public class Base64 extends BaseNCodec {
/**
* Base64 uses 6-bit fields.
*/
- /** Mask used to extract 6 bits, used when encoding */
+ /**
+ * Mask used to extract 6 bits, used when encoding
+ */
private static final int MASK_6BITS = 0x3f;
// The static final fields above are used for the original static byte[] methods on Base64.
@@ -202,9 +204,8 @@ public Base64() {
* When decoding all variants are supported.
*
*
- * @param urlSafe
- * if true, URL-safe encoding is used. In most cases this should be set to
- * false.
+ * @param urlSafe if true, URL-safe encoding is used. In most cases this should be set to
+ * false.
* @since 1.4
*/
public Base64(boolean urlSafe) {
@@ -224,9 +225,8 @@ public Base64(boolean urlSafe) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
* @since 1.4
*/
public Base64(int lineLength) {
@@ -246,13 +246,10 @@ public Base64(int lineLength) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @throws IllegalArgumentException
- * Thrown when the provided lineSeparator included some base64 characters.
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @throws IllegalArgumentException Thrown when the provided lineSeparator included some base64 characters.
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator) {
@@ -272,16 +269,12 @@ public Base64(int lineLength, byte[] lineSeparator) {
* When decoding all variants are supported.
*
*
- * @param lineLength
- * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
- * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
- * @param lineSeparator
- * Each line of encoded data will end with this sequence of bytes.
- * @param urlSafe
- * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
- * operations. Decoding seamlessly handles both modes.
- * @throws IllegalArgumentException
- * The provided lineSeparator included some base64 characters. That's not going to work!
+ * @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
+ * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
+ * @param lineSeparator Each line of encoded data will end with this sequence of bytes.
+ * @param urlSafe Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
+ * operations. Decoding seamlessly handles both modes.
+ * @throws IllegalArgumentException The provided lineSeparator included some base64 characters. That's not going to work!
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
@@ -295,7 +288,7 @@ public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
String sep = StringUtils.newStringUtf8(lineSeparator);
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
}
- if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE
+ if (lineLength > 0) { // null line-sep forces no chunking rather than throwing IAE
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
@@ -332,12 +325,9 @@ public boolean isUrlSafe() {
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*
*
- * @param in
- * byte[] array of binary data to base64 encode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of binary data to base64 encode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) {
if (eof) {
@@ -353,7 +343,7 @@ void encode(byte[] in, int inPos, int inAvail) {
ensureBufferSize(encodeSize);
int savedPos = pos;
switch (modulus) { // 0-2
- case 1 : // 8 bits = 6 + 2
+ case 1: // 8 bits = 6 + 2
buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS]; // top 6 bits
buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS]; // remaining 2
// URL-SAFE skips the padding to further reduce size.
@@ -363,7 +353,7 @@ void encode(byte[] in, int inPos, int inAvail) {
}
break;
- case 2 : // 16 bits = 6 + 6 + 4
+ case 2: // 16 bits = 6 + 6 + 4
buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
@@ -382,7 +372,7 @@ void encode(byte[] in, int inPos, int inAvail) {
} else {
for (int i = 0; i < inAvail; i++) {
ensureBufferSize(encodeSize);
- modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
int b = in[inPos++];
if (b < 0) {
b += 256;
@@ -420,12 +410,9 @@ void encode(byte[] in, int inPos, int inAvail) {
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*
*
- * @param in
- * byte[] array of ascii data to base64 decode.
- * @param inPos
- * Position to start reading data from.
- * @param inAvail
- * Amount of bytes available from input for encoding.
+ * @param in byte[] array of ascii data to base64 decode.
+ * @param inPos Position to start reading data from.
+ * @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
@@ -445,7 +432,7 @@ void decode(byte[] in, int inPos, int inAvail) {
if (b >= 0 && b < DECODE_TABLE.length) {
int result = DECODE_TABLE[b];
if (result >= 0) {
- modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
+ modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
if (modulus == 0) {
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
@@ -468,11 +455,11 @@ void decode(byte[] in, int inPos, int inAvail) {
switch (modulus) {
// case 1: // 6 bits - ignore entirely
// break;
- case 2 : // 12 bits = 8 + 4
+ case 2: // 12 bits = 8 + 4
bitWorkArea = bitWorkArea >> 4; // dump the extra 4 bits
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
break;
- case 3 : // 18 bits = 8 + 8 + 2
+ case 3: // 18 bits = 8 + 8 + 2
bitWorkArea = bitWorkArea >> 2; // dump 2 bits
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
@@ -484,8 +471,7 @@ void decode(byte[] in, int inPos, int inAvail) {
/**
* Returns whether or not the octet is in the base 64 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the base 64 alphabet, false otherwise.
* @since 1.4
*/
@@ -497,11 +483,10 @@ public static boolean isBase64(byte octet) {
* Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param base64
- * String to test
+ * @param base64 String to test
* @return true if all characters in the String are valid characters in the Base64 alphabet or if
- * the String is empty; false, otherwise
- * @since 1.5
+ * the String is empty; false, otherwise
+ * @since 1.5
*/
public static boolean isBase64(String base64) {
return isBase64(StringUtils.getBytesUtf8(base64));
@@ -511,10 +496,9 @@ public static boolean isBase64(String base64) {
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
* @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
*/
public static boolean isArrayByteBase64(byte[] arrayOctet) {
@@ -525,10 +509,9 @@ public static boolean isArrayByteBase64(byte[] arrayOctet) {
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
* @since 1.5
*/
public static boolean isBase64(byte[] arrayOctet) {
@@ -543,8 +526,7 @@ public static boolean isBase64(byte[] arrayOctet) {
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return byte[] containing Base64 characters in their UTF-8 representation.
*/
public static byte[] encodeBase64(byte[] binaryData) {
@@ -553,12 +535,11 @@ public static byte[] encodeBase64(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
- *
+ *
* NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
* single-line non-chunking (commons-codec-1.5).
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return String containing Base64 characters.
* @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
*/
@@ -570,8 +551,7 @@ public static String encodeBase64String(byte[] binaryData) {
* Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
* url-safe variation emits - and _ instead of + and / characters.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return byte[] containing Base64 characters in their UTF-8 representation.
* @since 1.4
*/
@@ -583,8 +563,7 @@ public static byte[] encodeBase64URLSafe(byte[] binaryData) {
* Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
* url-safe variation emits - and _ instead of + and / characters.
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return String containing Base64 characters
* @since 1.4
*/
@@ -595,8 +574,7 @@ public static String encodeBase64URLSafeString(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
*
- * @param binaryData
- * binary data to encode
+ * @param binaryData binary data to encode
* @return Base64 characters chunked in 76 character blocks
*/
public static byte[] encodeBase64Chunked(byte[] binaryData) {
@@ -606,13 +584,10 @@ public static byte[] encodeBase64Chunked(byte[] binaryData) {
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
return encodeBase64(binaryData, isChunked, false);
@@ -621,15 +596,11 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
- * @param urlSafe
- * if true this encoder will emit - and _ instead of the usual + and / characters.
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
+ * @param urlSafe if true this encoder will emit - and _ instead of the usual + and / characters.
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
* @since 1.4
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) {
@@ -639,17 +610,12 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
- * @param binaryData
- * Array containing binary data to encode.
- * @param isChunked
- * if true this encoder will chunk the base64 output into 76 character blocks
- * @param urlSafe
- * if true this encoder will emit - and _ instead of the usual + and / characters.
- * @param maxResultSize
- * The maximum result size to accept.
+ * @param binaryData Array containing binary data to encode.
+ * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks
+ * @param urlSafe if true this encoder will emit - and _ instead of the usual + and / characters.
+ * @param maxResultSize The maximum result size to accept.
* @return Base64-encoded data.
- * @throws IllegalArgumentException
- * Thrown when the input array needs an output array bigger than maxResultSize
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than maxResultSize
* @since 1.4
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
@@ -674,8 +640,7 @@ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean
/**
* Decodes a Base64 String into octets
*
- * @param base64String
- * String containing Base64 data
+ * @param base64String String containing Base64 data
* @return Array containing decoded data.
* @since 1.4
*/
@@ -686,8 +651,7 @@ public static byte[] decodeBase64(String base64String) {
/**
* Decodes Base64 data into octets
*
- * @param base64Data
- * Byte array containing Base64 data
+ * @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
@@ -697,11 +661,11 @@ public static byte[] decodeBase64(byte[] base64Data) {
// Implementation of the Encoder Interface
// Implementation of integer encoding used for crypto
+
/**
* Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
*
- * @param pArray
- * a byte array containing base64 character data
+ * @param pArray a byte array containing base64 character data
* @return A BigInteger
* @since 1.4
*/
@@ -712,11 +676,9 @@ public static BigInteger decodeInteger(byte[] pArray) {
/**
* Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
*
- * @param bigInt
- * a BigInteger
+ * @param bigInt a BigInteger
* @return A byte array containing base64 character data
- * @throws NullPointerException
- * if null is passed in
+ * @throws NullPointerException if null is passed in
* @since 1.4
*/
public static byte[] encodeInteger(BigInteger bigInt) {
@@ -729,8 +691,7 @@ public static byte[] encodeInteger(BigInteger bigInt) {
/**
* Returns a byte-array representation of a BigInteger without sign bit.
*
- * @param bigInt
- * BigInteger to be converted
+ * @param bigInt BigInteger to be converted
* @return a byte array representation of the BigInteger parameter
*/
static byte[] toIntegerBytes(BigInteger bigInt) {
@@ -760,8 +721,7 @@ static byte[] toIntegerBytes(BigInteger bigInt) {
/**
* Returns whether or not the octet is in the Base32 alphabet.
*
- * @param octet
- * The value to test
+ * @param octet The value to test
* @return true if the value is defined in the the Base32 alphabet false otherwise.
*/
protected boolean isInAlphabet(byte octet) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
index 632bc8ec..9151055f 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BaseNCodec.java
@@ -44,7 +44,7 @@
public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
- * MIME chunk size per RFC 2045 section 6.8.
+ * MIME chunk size per RFC 2045 section 6.8.
*
*
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
@@ -75,7 +75,9 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
- /** Mask used to extract 8 bits, used in decoding bytes */
+ /**
+ * Mask used to extract 8 bits, used in decoding bytes
+ */
protected static final int MASK_8BITS = 0xff;
/**
@@ -85,10 +87,14 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
- /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
+ /**
+ * Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32
+ */
private final int unencodedBlockSize;
- /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
+ /**
+ * Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
+ */
private final int encodedBlockSize;
/**
@@ -139,15 +145,16 @@ public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
* Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize}
* If chunkSeparatorLength is zero, then chunking is disabled.
- * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
- * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
- * @param lineLength if > 0, use chunking with a length lineLength
+ *
+ * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
+ * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
+ * @param lineLength if > 0, use chunking with a length lineLength
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
- protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength){
+ protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
- this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
+ this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
@@ -178,7 +185,9 @@ protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
- /** Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. */
+ /**
+ * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
+ */
private void resizeBuffer() {
if (buffer == null) {
buffer = new byte[getDefaultBufferSize()];
@@ -196,8 +205,8 @@ private void resizeBuffer() {
*
* @param size minimum spare space required
*/
- protected void ensureBufferSize(int size){
- if ((buffer == null) || (buffer.length < pos + size)){
+ protected void ensureBufferSize(int size) {
+ if ((buffer == null) || (buffer.length < pos + size)) {
resizeBuffer();
}
}
@@ -206,12 +215,9 @@ protected void ensureBufferSize(int size){
* Extracts buffered data into the provided byte[] array, starting at position bPos,
* up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.
*
- * @param b
- * byte[] array to extract the buffered data into.
- * @param bPos
- * position in byte[] array to start extraction at.
- * @param bAvail
- * amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
+ * @param b byte[] array to extract the buffered data into.
+ * @param bPos position in byte[] array to start extraction at.
+ * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(byte[] b, int bPos, int bAvail) { // package protected for access from I/O streams
@@ -230,18 +236,18 @@ int readResults(byte[] b, int bPos, int bAvail) { // package protected for acce
/**
* Checks if a byte value is whitespace or not.
* Whitespace is taken to mean: space, tab, CR, LF
- * @param byteToCheck
- * the byte to check
+ *
+ * @param byteToCheck the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(byte byteToCheck) {
switch (byteToCheck) {
- case ' ' :
- case '\n' :
- case '\r' :
- case '\t' :
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
return true;
- default :
+ default:
return false;
}
}
@@ -262,11 +268,9 @@ private void reset() {
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the
* Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
- * @param pObject
- * Object to encode
+ * @param pObject Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
- * @throws EncoderException
- * if the parameter supplied is not of type byte[]
+ * @throws EncoderException if the parameter supplied is not of type byte[]
*/
public Object encode(Object pObject) throws EncoderException {
if (!(pObject instanceof byte[])) {
@@ -278,8 +282,7 @@ public Object encode(Object pObject) throws EncoderException {
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
*
- * @param pArray
- * a byte array containing binary data
+ * @param pArray a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(byte[] pArray) {
@@ -290,11 +293,9 @@ public String encodeToString(byte[] pArray) {
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the
* Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
- * @param pObject
- * Object to decode
+ * @param pObject Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
- * @throws DecoderException
- * if the parameter supplied is not of type byte[]
+ * @throws DecoderException if the parameter supplied is not of type byte[]
*/
public Object decode(Object pObject) throws DecoderException {
if (pObject instanceof byte[]) {
@@ -309,8 +310,7 @@ public Object decode(Object pObject) throws DecoderException {
/**
* Decodes a String containing characters in the Base-N alphabet.
*
- * @param pArray
- * A String containing Base-N character data
+ * @param pArray A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(String pArray) {
@@ -320,8 +320,7 @@ public byte[] decode(String pArray) {
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
- * @param pArray
- * A byte array containing Base-N character data
+ * @param pArray A byte array containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(byte[] pArray) {
@@ -339,8 +338,7 @@ public byte[] decode(byte[] pArray) {
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
- * @param pArray
- * a byte array containing binary data
+ * @param pArray a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
public byte[] encode(byte[] pArray) {
@@ -362,7 +360,7 @@ public byte[] encode(byte[] pArray) {
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
- public String encodeAsString(byte[] pArray){
+ public String encodeAsString(byte[] pArray) {
return StringUtils.newStringUtf8(encode(pArray));
}
@@ -375,7 +373,6 @@ public String encodeAsString(byte[] pArray){
* Does not allow whitespace or pad.
*
* @param value The value to test
- *
* @return true if the value is defined in the current alphabet, false otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
@@ -386,9 +383,8 @@ public String encodeAsString(byte[] pArray){
*
* @param arrayOctet byte array to test
* @param allowWSPad if true, then whitespace and PAD are also allowed
- *
* @return true if all bytes are valid characters in the alphabet or if the byte array is empty;
- * false, otherwise
+ * false, otherwise
*/
public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
@@ -406,7 +402,7 @@ public boolean isInAlphabet(byte[] arrayOctet, boolean allowWSPad) {
*
* @param basen String to test
* @return true if all characters in the String are valid characters in the alphabet or if
- * the String is empty; false, otherwise
+ * the String is empty; false, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(String basen) {
@@ -415,11 +411,10 @@ public boolean isInAlphabet(String basen) {
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
- *
+ *
* Intended for use in checking line-ending arrays
*
- * @param arrayOctet
- * byte array to test
+ * @param arrayOctet byte array to test
* @return true if any byte is a valid character in the alphabet or PAD; false otherwise
*/
protected boolean containsAlphabetOrPad(byte[] arrayOctet) {
@@ -438,17 +433,16 @@ protected boolean containsAlphabetOrPad(byte[] arrayOctet) {
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
- *
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
*/
public long getEncodedLength(byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
- long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
+ long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
- len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
+ len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength;
}
return len;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
index 5472e43c..5a0afc83 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryCodec.java
@@ -36,47 +36,67 @@
/**
* Converts between byte arrays and strings of "0"s and "1"s.
- *
+ *
* TODO: may want to add more bit vector functions like and/or/xor/nand
* TODO: also might be good to generate boolean[] from byte[] et cetera.
*
* @author Apache Software Foundation
- * @since 1.3
* @version $Id$
+ * @since 1.3
*/
public class BinaryCodec implements BinaryDecoder, BinaryEncoder {
/*
* tried to avoid using ArrayUtils to minimize dependencies while using these empty arrays - dep is just not worth
* it.
*/
- /** Empty char array. */
+ /**
+ * Empty char array.
+ */
private static final char[] EMPTY_CHAR_ARRAY = new char[0];
- /** Empty byte array. */
+ /**
+ * Empty byte array.
+ */
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
- /** Mask for bit 0 of a byte. */
+ /**
+ * Mask for bit 0 of a byte.
+ */
private static final int BIT_0 = 1;
- /** Mask for bit 1 of a byte. */
+ /**
+ * Mask for bit 1 of a byte.
+ */
private static final int BIT_1 = 0x02;
- /** Mask for bit 2 of a byte. */
+ /**
+ * Mask for bit 2 of a byte.
+ */
private static final int BIT_2 = 0x04;
- /** Mask for bit 3 of a byte. */
+ /**
+ * Mask for bit 3 of a byte.
+ */
private static final int BIT_3 = 0x08;
- /** Mask for bit 4 of a byte. */
+ /**
+ * Mask for bit 4 of a byte.
+ */
private static final int BIT_4 = 0x10;
- /** Mask for bit 5 of a byte. */
+ /**
+ * Mask for bit 5 of a byte.
+ */
private static final int BIT_5 = 0x20;
- /** Mask for bit 6 of a byte. */
+ /**
+ * Mask for bit 6 of a byte.
+ */
private static final int BIT_6 = 0x40;
- /** Mask for bit 7 of a byte. */
+ /**
+ * Mask for bit 7 of a byte.
+ */
private static final int BIT_7 = 0x80;
private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7};
@@ -84,8 +104,7 @@ public class BinaryCodec implements BinaryDecoder, BinaryEncoder {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return 0 and 1 ASCII character bytes one for each bit of the argument
*/
public byte[] encode(byte[] raw) {
@@ -95,11 +114,9 @@ public byte[] encode(byte[] raw) {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 chars.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return 0 and 1 ASCII character chars one for each bit of the argument
- * @throws EncoderException
- * if the argument is not a byte[]
+ * @throws EncoderException if the argument is not a byte[]
*/
public Object encode(Object raw) throws EncoderException {
if (!(raw instanceof byte[])) {
@@ -111,11 +128,9 @@ public Object encode(Object raw) throws EncoderException {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
- * @throws DecoderException
- * if argument is not a byte[], char[] or String
+ * @throws DecoderException if argument is not a byte[], char[] or String
*/
public Object decode(Object ascii) throws DecoderException {
if (ascii == null) {
@@ -136,8 +151,7 @@ public Object decode(Object ascii) throws DecoderException {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public byte[] decode(byte[] ascii) {
@@ -147,8 +161,7 @@ public byte[] decode(byte[] ascii) {
/**
* Decodes a String where each char of the String represents an ASCII '0' or '1'.
*
- * @param ascii
- * String of '0' and '1' characters
+ * @param ascii String of '0' and '1' characters
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public byte[] toByteArray(String ascii) {
@@ -163,11 +176,11 @@ public byte[] toByteArray(String ascii) {
// static codec operations
//
// ------------------------------------------------------------------------
+
/**
* Decodes a char array where each char represents an ASCII '0' or '1'.
*
- * @param ascii
- * each char represents an ASCII '0' or '1'
+ * @param ascii each char represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a char in the char array argument
*/
public static byte[] fromAscii(char[] ascii) {
@@ -193,8 +206,7 @@ public static byte[] fromAscii(char[] ascii) {
/**
* Decodes a byte array where each byte represents an ASCII '0' or '1'.
*
- * @param ascii
- * each byte represents an ASCII '0' or '1'
+ * @param ascii each byte represents an ASCII '0' or '1'
* @return the raw encoded binary where each bit corresponds to a byte in the byte array argument
*/
public static byte[] fromAscii(byte[] ascii) {
@@ -220,8 +232,7 @@ public static byte[] fromAscii(byte[] ascii) {
/**
* Returns true if the given array is null or empty (size 0.)
*
- * @param array
- * the source array
+ * @param array the source array
* @return true if the given array is null or empty (size 0.)
*/
private static boolean isEmpty(byte[] array) {
@@ -232,8 +243,7 @@ private static boolean isEmpty(byte[] array) {
* Converts an array of raw binary data into an array of ASCII 0 and 1 character bytes - each byte is a truncated
* char.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return an array of 0 and 1 character bytes for each bit of the argument
*/
public static byte[] toAsciiBytes(byte[] raw) {
@@ -261,8 +271,7 @@ public static byte[] toAsciiBytes(byte[] raw) {
/**
* Converts an array of raw binary data into an array of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return an array of 0 and 1 characters for each bit of the argument
*/
public static char[] toAsciiChars(byte[] raw) {
@@ -290,8 +299,7 @@ public static char[] toAsciiChars(byte[] raw) {
/**
* Converts an array of raw binary data into a String of ASCII 0 and 1 characters.
*
- * @param raw
- * the raw binary data to convert
+ * @param raw the raw binary data to convert
* @return a String of 0 and 1 characters representing the binary data
*/
public static String toAsciiString(byte[] raw) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
index 1291e457..89cf14cd 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryDecoder.java
@@ -46,13 +46,11 @@ public interface BinaryDecoder extends Decoder {
* Decodes a byte array and returns the results as a byte array.
*
* @param source A byte array which has been encoded with the
- * appropriate encoder
- *
+ * appropriate encoder
* @return a byte array that contains decoded content
- *
* @throws DecoderException A decoder exception is thrown
- * if a Decoder encounters a failure condition during
- * the decode process.
+ * if a Decoder encounters a failure condition during
+ * the decode process.
*/
byte[] decode(byte[] source) throws DecoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
index d5363df4..b4cb04ce 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/BinaryEncoder.java
@@ -46,12 +46,10 @@ public interface BinaryEncoder extends Encoder {
* as a byte array.
*
* @param source Data to be encoded
- *
* @return A byte array containing the encoded data
- *
* @throws EncoderException thrown if the Encoder
- * encounters a failure condition during the
- * encoding process.
+ * encounters a failure condition during the
+ * encoding process.
*/
byte[] encode(byte[] source) throws EncoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
index 97324597..297c4e3e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/CharEncoding.java
@@ -35,7 +35,7 @@
/**
* Character encoding names required of every implementation of the Java platform.
- *
+ *
@@ -59,14 +59,14 @@
* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
* accepted on input, big-endian used on output.)
*
- *
+ *
* This perhaps would best belong in the [lang] project. Even if a similar interface is defined in [lang], it is not
* forseen that [codec] would be made to depend on [lang].
*
- * @see Standard charsets
* @author Apache Software Foundation
- * @since 1.4
* @version $Id$
+ * @see Standard charsets
+ * @since 1.4
*/
public class CharEncoding {
/**
@@ -139,4 +139,4 @@ public class CharEncoding {
* @see Standard charsets
*/
public static final String UTF_8 = "UTF-8";
-}
\ No newline at end of file
+}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java
index d90a8f6c..cd2aab62 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Decoder.java
@@ -58,14 +58,12 @@ public interface Decoder {
* this decode method will throw a DecoderException.
*
* @param source the object to decode
- *
* @return a 'decoded" object
- *
* @throws DecoderException a decoder exception can
- * be thrown for any number of reasons. Some good
- * candidates are that the parameter passed to this
- * method is null, a param cannot be cast to the
- * appropriate type for a specific encoder.
+ * be thrown for any number of reasons. Some good
+ * candidates are that the parameter passed to this
+ * method is null, a param cannot be cast to the
+ * appropriate type for a specific encoder.
*/
Object decode(Object source) throws DecoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java
index dd8ebe5e..6475647f 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/DecoderException.java
@@ -63,8 +63,7 @@ public DecoderException() {
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
* be initialized by a call to {@link #initCause}.
*
- * @param message
- * The detail message which is saved for later retrieval by the {@link #getMessage()} method.
+ * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method.
*/
public DecoderException(String message) {
super(message);
@@ -78,11 +77,9 @@ public DecoderException(String message) {
* exception's detail message.
*
*
- * @param message
- * The detail message which is saved for later retrieval by the {@link #getMessage()} method.
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(String message, Throwable cause) {
@@ -94,9 +91,8 @@ public DecoderException(String message, Throwable cause) {
* null : cause.toString()) (which typically contains the class and detail message of cause).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(Throwable cause) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
index bb6208dc..17626e2b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Encoder.java
@@ -50,12 +50,10 @@ public interface Encoder {
* or Strings depending on the implementation used.
*
* @param source An object ot encode
- *
* @return An "encoded" Object
- *
* @throws EncoderException an encoder exception is
- * thrown if the encoder experiences a failure
- * condition during the encoding process.
+ * thrown if the encoder experiences a failure
+ * condition during the encoding process.
*/
Object encode(Object source) throws EncoderException;
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
index 5c831c23..839aee36 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/EncoderException.java
@@ -64,8 +64,7 @@ public EncoderException() {
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
* be initialized by a call to {@link #initCause}.
*
- * @param message
- * a useful message relating to the encoder specific error.
+ * @param message a useful message relating to the encoder specific error.
*/
public EncoderException(String message) {
super(message);
@@ -79,11 +78,9 @@ public EncoderException(String message) {
* exception's detail message.
*
*
- * @param message
- * The detail message which is saved for later retrieval by the {@link #getMessage()} method.
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param message The detail message which is saved for later retrieval by the {@link #getMessage()} method.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(String message, Throwable cause) {
@@ -95,9 +92,8 @@ public EncoderException(String message, Throwable cause) {
* null : cause.toString()) (which typically contains the class and detail message of cause).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
- * @param cause
- * The cause which is saved for later retrieval by the {@link #getCause()} method. A null
- * value is permitted, and indicates that the cause is nonexistent or unknown.
+ * @param cause The cause which is saved for later retrieval by the {@link #getCause()} method. A null
+ * value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(Throwable cause) {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
index b241d389..33dcaaf9 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/Hex.java
@@ -39,9 +39,9 @@
* Converts hexadecimal Strings. The charset used for certain operation can be set, the default is set in
* {@link #DEFAULT_CHARSET_NAME}
*
- * @since 1.1
* @author Apache Software Foundation
* @version $Id$
+ * @since 1.1
*/
public class Hex implements BinaryEncoder, BinaryDecoder {
@@ -67,11 +67,9 @@ public class Hex implements BinaryEncoder, BinaryDecoder {
* returned array will be half the length of the passed array, as it takes two characters to represent any given
* byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param data
- * An array of characters containing hexadecimal digits
+ * @param data An array of characters containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied char array.
- * @throws DecoderException
- * Thrown if an odd number or illegal of characters is supplied
+ * @throws DecoderException Thrown if an odd number or illegal of characters is supplied
*/
public static byte[] decodeHex(char[] data) throws DecoderException {
@@ -100,8 +98,7 @@ public static byte[] decodeHex(char[] data) throws DecoderException {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
+ * @param data a byte[] to convert to Hex characters
* @return A char[] containing hexadecimal characters
*/
public static char[] encodeHex(byte[] data) {
@@ -113,10 +110,8 @@ public static char[] encodeHex(byte[] data) {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
- * @param toLowerCase
- * true converts to lowercase, false to uppercase
+ * @param data a byte[] to convert to Hex characters
+ * @param toLowerCase true converts to lowercase, false to uppercase
* @return A char[] containing hexadecimal characters
* @since 1.4
*/
@@ -129,10 +124,8 @@ public static char[] encodeHex(byte[] data, boolean toLowerCase) {
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
- * @param toDigits
- * the output alphabet
+ * @param data a byte[] to convert to Hex characters
+ * @param toDigits the output alphabet
* @return A char[] containing hexadecimal characters
* @since 1.4
*/
@@ -151,8 +144,7 @@ protected static char[] encodeHex(byte[] data, char[] toDigits) {
* Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned
* String will be double the length of the passed array, as it takes two characters to represent any given byte.
*
- * @param data
- * a byte[] to convert to Hex characters
+ * @param data a byte[] to convert to Hex characters
* @return A String containing hexadecimal characters
* @since 1.4
*/
@@ -163,13 +155,10 @@ public static String encodeHexString(byte[] data) {
/**
* Converts a hexadecimal character to an integer.
*
- * @param ch
- * A character to convert to an integer digit
- * @param index
- * The index of the character in the source
+ * @param ch A character to convert to an integer digit
+ * @param index The index of the character in the source
* @return An integer
- * @throws DecoderException
- * Thrown if ch is an illegal hex character
+ * @throws DecoderException Thrown if ch is an illegal hex character
*/
protected static int toDigit(char ch, int index) throws DecoderException {
int digit = Character.digit(ch, 16);
@@ -192,8 +181,7 @@ public Hex() {
/**
* Creates a new codec with the given charset name.
*
- * @param csName
- * the charset name.
+ * @param csName the charset name.
* @since 1.4
*/
public Hex(String csName) {
@@ -205,11 +193,9 @@ public Hex(String csName) {
* The returned array will be half the length of the passed array, as it takes two characters to represent any given
* byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param array
- * An array of character bytes containing hexadecimal digits
+ * @param array An array of character bytes containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
- * @throws DecoderException
- * Thrown if an odd number of characters is supplied to this function
+ * @throws DecoderException Thrown if an odd number of characters is supplied to this function
* @see #decodeHex(char[])
*/
public byte[] decode(byte[] array) throws DecoderException {
@@ -225,12 +211,10 @@ public byte[] decode(byte[] array) throws DecoderException {
* same values. The returned array will be half the length of the passed String or array, as it takes two characters
* to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
*
- * @param object
- * A String or, an array of character bytes containing hexadecimal digits
+ * @param object A String or, an array of character bytes containing hexadecimal digits
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
- * @throws DecoderException
- * Thrown if an odd number of characters is supplied to this function or the object is not a String or
- * char[]
+ * @throws DecoderException Thrown if an odd number of characters is supplied to this function or the object is not a String or
+ * char[]
* @see #decodeHex(char[])
*/
public Object decode(Object object) throws DecoderException {
@@ -251,12 +235,10 @@ public Object decode(Object object) throws DecoderException {
* {@link #getCharsetName()}.
*
*
- * @param array
- * a byte[] to convert to Hex characters
+ * @param array a byte[] to convert to Hex characters
* @return A byte[] containing the bytes of the hexadecimal characters
- * @throws IllegalStateException
- * if the charsetName is invalid. This API throws {@link IllegalStateException} instead of
- * {@link UnsupportedEncodingException} for backward compatibility.
+ * @throws IllegalStateException if the charsetName is invalid. This API throws {@link IllegalStateException} instead of
+ * {@link UnsupportedEncodingException} for backward compatibility.
* @see #encodeHex(byte[])
*/
public byte[] encode(byte[] array) {
@@ -272,11 +254,9 @@ public byte[] encode(byte[] array) {
* {@link #getCharsetName()}.
*
*
- * @param object
- * a String, or byte[] to convert to Hex characters
+ * @param object a String, or byte[] to convert to Hex characters
* @return A char[] containing hexadecimal characters
- * @throws EncoderException
- * Thrown if the given object is not a String or byte[]
+ * @throws EncoderException Thrown if the given object is not a String or byte[]
* @see #encodeHex(byte[])
*/
public Object encode(Object object) throws EncoderException {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java b/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
index 1c7781bf..dd7f55c3 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/codec/StringUtils.java
@@ -40,10 +40,10 @@
* Converts String to and from bytes using the encodings required by the Java specification. These encodings are specified in Standard charsets
*
- * @see CharEncoding
- * @see Standard charsets
* @author Gary Gregory
* @version $Id$
+ * @see CharEncoding
+ * @see Standard charsets
* @since 1.4
*/
public class StringUtils {
@@ -52,11 +52,9 @@ public class StringUtils {
* Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing the result into a new
* byte array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -68,11 +66,9 @@ public static byte[] getBytesIso8859_1(String string) {
* Encodes the given string into a sequence of bytes using the US-ASCII charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -84,11 +80,9 @@ public static byte[] getBytesUsAscii(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16 charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -100,11 +94,9 @@ public static byte[] getBytesUtf16(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16BE charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -116,11 +108,9 @@ public static byte[] getBytesUtf16Be(String string) {
* Encodes the given string into a sequence of bytes using the UTF-16LE charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -132,11 +122,9 @@ public static byte[] getBytesUtf16Le(String string) {
* Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
* array.
*
- * @param string
- * the String to encode, may be null
+ * @param string the String to encode, may be null
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when the charset is missing, which should be never according the the Java specification.
+ * @throws IllegalStateException Thrown when the charset is missing, which should be never according the the Java specification.
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
@@ -152,14 +140,11 @@ public static byte[] getBytesUtf8(String string) {
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
*
*
- * @param string
- * the String to encode, may be null
- * @param charsetName
- * The name of a required {@link java.nio.charset.Charset}
+ * @param string the String to encode, may be null
+ * @param charsetName The name of a required {@link java.nio.charset.Charset}
* @return encoded bytes, or null if the input string was null
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
- * required charset name.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
+ * required charset name.
* @see CharEncoding
* @see String#getBytes(String)
*/
@@ -185,15 +170,12 @@ private static IllegalStateException newIllegalStateException(String charsetName
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
*
*
- * @param bytes
- * The bytes to be decoded into characters, may be null
- * @param charsetName
- * The name of a required {@link java.nio.charset.Charset}
+ * @param bytes The bytes to be decoded into characters, may be null
+ * @param charsetName The name of a required {@link java.nio.charset.Charset}
* @return A new String decoded from the specified array of bytes using the given charset,
- * or null if the input byte arrray was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
- * required charset name.
+ * or null if the input byte arrray was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
+ * required charset name.
* @see CharEncoding
* @see String#String(byte[], String)
*/
@@ -211,13 +193,11 @@ public static String newString(byte[] bytes, String charsetName) {
/**
* Constructs a new String by decoding the specified array of bytes using the ISO-8859-1 charset.
*
- * @param bytes
- * The bytes to be decoded into characters, may be null
+ * @param bytes The bytes to be decoded into characters, may be null
* @return A new String decoded from the specified array of bytes using the ISO-8859-1 charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringIso8859_1(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.ISO_8859_1);
@@ -226,13 +206,11 @@ public static String newStringIso8859_1(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the US-ASCII charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the US-ASCII charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUsAscii(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.US_ASCII);
@@ -241,13 +219,11 @@ public static String newStringUsAscii(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16 charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16 charset
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16);
@@ -256,13 +232,11 @@ public static String newStringUtf16(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16BE charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16BE charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16Be(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16BE);
@@ -271,13 +245,11 @@ public static String newStringUtf16Be(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-16LE charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-16LE charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf16Le(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_16LE);
@@ -286,13 +258,11 @@ public static String newStringUtf16Le(byte[] bytes) {
/**
* Constructs a new String by decoding the specified array of bytes using the UTF-8 charset.
*
- * @param bytes
- * The bytes to be decoded into characters
+ * @param bytes The bytes to be decoded into characters
* @return A new String decoded from the specified array of bytes using the UTF-8 charset,
- * or null if the input byte array was null.
- * @throws IllegalStateException
- * Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
- * charset is required.
+ * or null if the input byte array was null.
+ * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
+ * charset is required.
*/
public static String newStringUtf8(byte[] bytes) {
return StringUtils.newString(bytes, CharEncoding.UTF_8);
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java b/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
index 78e2bd53..92c97572 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/federation/Federation.java
@@ -6,39 +6,40 @@
* @see Federation docs
*/
public class Federation {
- private Federation() {
- }
+ private Federation() {
+ }
- /**
- * This method is a helper method for handling user inputs that contain `destination` value.
- * It accepts two types of values:
- *
- *
For Stellar address (ex. bob*stellar.org`) it splits Stellar address and then tries to find information about
- * federation server in stellar.toml file for a given domain.
- *
For account ID (ex. GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS) it simply returns the
- * given Account ID.
- *
- * @param value Stellar address or account id
- * @throws MalformedAddressException Address is malformed
- * @throws ConnectionErrorException Connection problems
- * @throws NoFederationServerException Stellar.toml does not contain federation server info
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
- * @throws NotFoundException Stellar address not found by federation server
- * @throws ServerErrorException Federation server responded with error
- * @return FederationResponse
- */
- public static FederationResponse resolve(String value) {
- String[] tokens = value.split("\\*");
- if (tokens.length == 1) {
- // accountId
- return new FederationResponse(null, value, null, null);
- } else if (tokens.length == 2) {
- String domain = tokens[1];
- FederationServer server = FederationServer.createForDomain(domain);
- return server.resolveAddress(value);
- } else {
- throw new MalformedAddressException();
+ /**
+ * This method is a helper method for handling user inputs that contain `destination` value.
+ * It accepts two types of values:
+ *
+ *
For Stellar address (ex. bob*stellar.org`) it splits Stellar address and then tries to find information about
+ * federation server in stellar.toml file for a given domain.
+ *
For account ID (ex. GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS) it simply returns the
+ * given Account ID.
+ *
+ *
+ * @param value Stellar address or account id
+ * @return FederationResponse
+ * @throws MalformedAddressException Address is malformed
+ * @throws ConnectionErrorException Connection problems
+ * @throws NoFederationServerException Stellar.toml does not contain federation server info
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
+ * @throws NotFoundException Stellar address not found by federation server
+ * @throws ServerErrorException Federation server responded with error
+ */
+ public static FederationResponse resolve(String value) {
+ String[] tokens = value.split("\\*");
+ if (tokens.length == 1) {
+ // accountId
+ return new FederationResponse(null, value, null, null);
+ } else if (tokens.length == 2) {
+ String domain = tokens[1];
+ FederationServer server = FederationServer.createForDomain(domain);
+ return server.resolveAddress(value);
+ } else {
+ throw new MalformedAddressException();
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationResponse.java
index 1bf48fdf..d6b5fe41 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationResponse.java
@@ -4,44 +4,45 @@
/**
* Object to hold a response from a federation server.
+ *
* @see Federation docs
*/
public class FederationResponse {
- @SerializedName("stellar_address")
- private final String stellarAddress;
- @SerializedName("account_id")
- private final String accountId;
- @SerializedName("memo_type")
- private final String memoType;
- @SerializedName("memo")
- private final String memo;
+ @SerializedName("stellar_address")
+ private final String stellarAddress;
+ @SerializedName("account_id")
+ private final String accountId;
+ @SerializedName("memo_type")
+ private final String memoType;
+ @SerializedName("memo")
+ private final String memo;
- public FederationResponse(String stellarAddress, String accountId, String memoType, String memo) {
- this.stellarAddress = stellarAddress;
- this.accountId = accountId;
- this.memoType = memoType;
- this.memo = memo;
- }
+ public FederationResponse(String stellarAddress, String accountId, String memoType, String memo) {
+ this.stellarAddress = stellarAddress;
+ this.accountId = accountId;
+ this.memoType = memoType;
+ this.memo = memo;
+ }
- public String getStellarAddress() {
- return stellarAddress;
- }
+ public String getStellarAddress() {
+ return stellarAddress;
+ }
- public String getAccountId() {
- return accountId;
- }
+ public String getAccountId() {
+ return accountId;
+ }
- /**
- * @return Memo type or null when no memo attached
- */
- public String getMemoType() {
- return memoType;
- }
+ /**
+ * @return Memo type or null when no memo attached
+ */
+ public String getMemoType() {
+ return memoType;
+ }
- /**
- * @return Memo value or null when no memo attached
- */
- public String getMemo() {
- return memo;
- }
+ /**
+ * @return Memo value or null when no memo attached
+ */
+ public String getMemo() {
+ return memo;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationServer.java b/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationServer.java
index 8751a65b..9f0acc09 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationServer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/federation/FederationServer.java
@@ -1,13 +1,17 @@
package kin.base.federation;
-import android.net.Uri;
import com.google.gson.reflect.TypeToken;
import com.moandjiezana.toml.Toml;
+
import java.io.IOException;
+import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.net.URL;
+
import kin.base.requests.ResponseHandler;
import kin.base.responses.HttpResponseException;
+import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@@ -24,161 +28,160 @@
* @see Federation docs
*/
public class FederationServer {
- private final URI serverUri;
- private final String domain;
- private static OkHttpClient httpClient = new OkHttpClient();
-
- /**
- * Creates a new FederationServer instance.
- *
- * @param serverUri Federation Server URI
- * @param domain Domain name this federation server is responsible for
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- */
- public FederationServer(URI serverUri, String domain) {
- this.serverUri = serverUri;
- if (this.serverUri.getScheme() != "https") {
- throw new FederationServerInvalidException();
+ private final URL serverUri;
+ private final String domain;
+ private static OkHttpClient httpClient = new OkHttpClient();
+
+ /**
+ * Creates a new FederationServer instance.
+ *
+ * @param serverUri Federation Server URI
+ * @param domain Domain name this federation server is responsible for
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ */
+ public FederationServer(URL serverUri, String domain) {
+ this.serverUri = serverUri;
+ if (!this.serverUri.getProtocol().equals("https")) {
+ throw new FederationServerInvalidException();
+ }
+ this.domain = domain;
}
- this.domain = domain;
- }
-
- /**
- * Creates a new FederationServer instance.
- *
- * @param serverUri Federation Server URI
- * @param domain Domain name this federation server is responsible for
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- */
- public FederationServer(String serverUri, String domain) {
- try {
- this.serverUri = new URI(serverUri);
- } catch (URISyntaxException e) {
- throw new FederationServerInvalidException();
+
+ /**
+ * Creates a new FederationServer instance.
+ *
+ * @param serverUri Federation Server URI
+ * @param domain Domain name this federation server is responsible for
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ */
+ public FederationServer(String serverUri, String domain) {
+ try {
+ this.serverUri = new URL(serverUri);
+ } catch (MalformedURLException e) {
+ throw new FederationServerInvalidException();
+ }
+ this.domain = domain;
}
- this.domain = domain;
- }
-
- /**
- * Creates a FederationServer instance for a given domain.
- * It tries to find a federation server URL in stellar.toml file.
- *
- * @param domain Domain to find a federation server for
- * @return FederationServer
- * @throws ConnectionErrorException Connection problems
- * @throws NoFederationServerException Stellar.toml does not contain federation server info
- * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
- * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
- * @see Stellar.toml docs
- */
- public static FederationServer createForDomain(String domain) {
- URI stellarTomlUri;
- try {
- StringBuilder uriBuilder = new StringBuilder();
- uriBuilder.append("https://");
- uriBuilder.append(domain);
- uriBuilder.append("/.well-known/stellar.toml");
- stellarTomlUri = new URI(uriBuilder.toString());
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
+
+ /**
+ * Creates a FederationServer instance for a given domain.
+ * It tries to find a federation server URL in stellar.toml file.
+ *
+ * @param domain Domain to find a federation server for
+ * @return FederationServer
+ * @throws ConnectionErrorException Connection problems
+ * @throws NoFederationServerException Stellar.toml does not contain federation server info
+ * @throws FederationServerInvalidException Federation server is invalid (malformed URL, not HTTPS, etc.)
+ * @throws StellarTomlNotFoundInvalidException Stellar.toml file was not found or was malformed.
+ * @see Stellar.toml docs
+ */
+ public static FederationServer createForDomain(String domain) {
+ URI stellarTomlUri;
+ try {
+ StringBuilder uriBuilder = new StringBuilder();
+ uriBuilder.append("https://");
+ uriBuilder.append(domain);
+ uriBuilder.append("/.well-known/stellar.toml");
+ stellarTomlUri = new URI(uriBuilder.toString());
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ Toml stellarToml = null;
+ try {
+ Request request = new Request.Builder().get()
+ .url(stellarTomlUri.toString())
+ .build();
+ Response response = httpClient.newCall(request)
+ .execute();
+ if (response.code() >= 300) {
+ throw new StellarTomlNotFoundInvalidException();
+ }
+ ResponseBody body = response.body();
+ if (body == null) {
+ throw new StellarTomlNotFoundInvalidException();
+ }
+ stellarToml = new Toml().read(body.string());
+ } catch (IOException e) {
+ throw new ConnectionErrorException();
+ }
+
+ String federationServer = stellarToml.getString("FEDERATION_SERVER");
+ if (federationServer == null) {
+ throw new NoFederationServerException();
+ }
+
+ return new FederationServer(federationServer, domain);
}
- Toml stellarToml = null;
- try {
- Request request = new Request.Builder().get()
- .url(stellarTomlUri.toString())
- .build();
- Response response = httpClient.newCall(request)
- .execute();
- if (response.code() >= 300) {
- throw new StellarTomlNotFoundInvalidException();
- }
- ResponseBody body = response.body();
- if (body == null) {
- throw new StellarTomlNotFoundInvalidException();
- }
- stellarToml = new Toml().read(body.string());
- } catch (IOException e) {
- throw new ConnectionErrorException();
+
+ /**
+ * Resolves a stellar address using a given federation server.
+ *
+ * @param address Stellar addres, like bob*stellar.org
+ * @return FederationResponse
+ * @throws MalformedAddressException Address is malformed
+ * @throws ConnectionErrorException Connection problems
+ * @throws NotFoundException Stellar address not found by federation server
+ * @throws ServerErrorException Federation server responded with error
+ */
+ public FederationResponse resolveAddress(String address) {
+ String[] tokens = address.split("\\*");
+ if (tokens.length != 2) {
+ throw new MalformedAddressException();
+ }
+
+ URL uri = HttpUrl.parse(serverUri.toString()).newBuilder()
+ .addQueryParameter("type", "name")
+ .addQueryParameter("q", address)
+ .build().url();
+
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+
+ Request request = new Request.Builder()
+ .url(uri.toString())
+ .get()
+ .build();
+
+ try {
+ Response response = httpClient.newCall(request)
+ .execute();
+ return responseHandler.handleResponse(response);
+ } catch (HttpResponseException e) {
+ if (e.getStatusCode() == 404) {
+ throw new NotFoundException();
+ } else {
+ throw new ServerErrorException();
+ }
+ } catch (IOException e) {
+ throw new ConnectionErrorException();
+ }
}
- String federationServer = stellarToml.getString("FEDERATION_SERVER");
- if (federationServer == null) {
- throw new NoFederationServerException();
+ /**
+ * Returns a federation server URI.
+ *
+ * @return URI
+ */
+ public URL getServerUri() {
+ return serverUri;
}
- return new FederationServer(federationServer, domain);
- }
-
- /**
- * Resolves a stellar address using a given federation server.
- *
- * @param address Stellar addres, like bob*stellar.org
- * @return FederationResponse
- * @throws MalformedAddressException Address is malformed
- * @throws ConnectionErrorException Connection problems
- * @throws NotFoundException Stellar address not found by federation server
- * @throws ServerErrorException Federation server responded with error
- */
- public FederationResponse resolveAddress(String address) {
- String[] tokens = address.split("\\*");
- if (tokens.length != 2) {
- throw new MalformedAddressException();
+ /**
+ * Returns a domain this server is responsible for.
+ *
+ * @return InternetDomainName
+ */
+ public String getDomain() {
+ return domain;
}
- Uri uri = Uri.parse(serverUri.toString())
- .buildUpon()
- .appendQueryParameter("type", "name")
- .appendQueryParameter("q", address)
- .build();
-
- TypeToken type = new TypeToken() {
- };
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
-
- Request request = new Request.Builder()
- .url(uri.toString())
- .get()
- .build();
-
- try {
- Response response = httpClient.newCall(request)
- .execute();
- return responseHandler.handleResponse(response);
- } catch (HttpResponseException e) {
- if (e.getStatusCode() == 404) {
- throw new NotFoundException();
- } else {
- throw new ServerErrorException();
- }
- } catch (IOException e) {
- throw new ConnectionErrorException();
+ /**
+ * To support mocking a client
+ *
+ * @param httpClient
+ */
+ static void setHttpClient(OkHttpClient httpClient) {
+ FederationServer.httpClient = httpClient;
}
- }
-
- /**
- * Returns a federation server URI.
- *
- * @return URI
- */
- public URI getServerUri() {
- return serverUri;
- }
-
- /**
- * Returns a domain this server is responsible for.
- *
- * @return InternetDomainName
- */
- public String getDomain() {
- return domain;
- }
-
- /**
- * To support mocking a client
- *
- * @param httpClient
- */
- static void setHttpClient(OkHttpClient httpClient) {
- FederationServer.httpClient = httpClient;
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/AccountsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/AccountsRequestBuilder.java
index 019c2b79..5cdbea37 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/AccountsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/AccountsRequestBuilder.java
@@ -2,42 +2,100 @@
import com.google.gson.reflect.TypeToken;
import com.here.oksse.ServerSentEvent;
+<<<<<<< HEAD
+=======
+
import java.io.IOException;
import java.net.URI;
+
+>>>>>>> master
import kin.base.KeyPair;
import kin.base.responses.AccountResponse;
+import kin.base.responses.AggregatedBalanceResponse;
+import kin.base.responses.ControlledAccountsResponse;
import kin.base.responses.Page;
import okhttp3.OkHttpClient;
+import java.io.IOException;
+import java.net.URI;
+
/**
* Builds requests connected to accounts.
*/
public class AccountsRequestBuilder extends RequestBuilder {
- public AccountsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "accounts");
+ public AccountsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "accounts");
+ }
+
+ /**
+ * Requests specific uri and returns {@link AccountResponse}.
+ * This method is helpful for getting the links.
+ *
+ * @throws IOException
+ */
+ public AccountResponse account(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Requests GET /accounts/{account}
+ *
+ * @param account Account to fetch
+ * @throws IOException
+ * @see Account Details
+ */
+ public AccountResponse account(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId());
+ return this.account(this.buildUri());
+ }
+
+<<<<<<< HEAD
+ /**
+ * Requests GET /accounts/{account}/aggregate_balance
+ *
+ * @param account Account to fetch the aggregated balance for.
+ */
+ public AggregatedBalanceResponse aggregateBalance(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId(), "aggregate_balance");
+ return this.aggregateBalance(this.buildUri());
}
/**
- * Requests specific uri and returns {@link AccountResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
+ * Requests specific uri and returns {@link AggregatedBalanceResponse}. This method is helpful for
+ * getting the links.
*/
- public AccountResponse account(URI uri) throws IOException {
- TypeToken type = new TypeToken() {};
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ public AggregatedBalanceResponse aggregateBalance(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(
+ httpClient, type);
return responseHandler.handleGetRequest(uri);
}
/**
- * Requests GET /accounts/{account}
- * @see Account Details
- * @param account Account to fetch
- * @throws IOException
+ * Requests GET /accounts/{account}/controlled_accounts
+ *
+ * @param account the account in which we get all his controlled accounts
+ */
+ public ControlledAccountsResponse controlledAccounts(KeyPair account) throws IOException {
+ this.setSegments("accounts", account.getAccountId(), "controlled_accounts");
+ return this.controlledAccounts(this.buildUri());
+ }
+
+ /**
+ * Requests specific uri and returns {@link ControlledAccountsResponse}. This method is helpful for
+ * getting the links.
*/
- public AccountResponse account(KeyPair account) throws IOException {
- this.setSegments("accounts", account.getAccountId());
- return this.account(this.buildUri());
+ public ControlledAccountsResponse controlledAccounts(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(
+ httpClient, type);
+ return responseHandler.handleGetRequest(uri);
}
/**
@@ -54,47 +112,78 @@ public static Page execute(OkHttpClient httpClient, URI uri)
type);
return responseHandler.handleGetRequest(uri);
}
+=======
+ /**
+ * Requests specific uri and returns {@link Page} of {@link AccountResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link AccountResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient,
+ type);
+ return responseHandler.handleGetRequest(uri);
+ }
+>>>>>>> master
- /**
- * Allows to stream SSE events from horizon.
- * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
- * This mode will keep the connection to horizon open and horizon will continue to return
- * responses as ledgers close.
- * @see Server-Sent Events
- * @see Response Format documentation
- * @param listener {@link EventListener} implementation with {@link AccountResponse} type
- * @return ServerSentEvent object, so you can close() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListener listener) {
- return new StreamHandler<>(new TypeToken() {})
- .handleStream(this.buildUri(),listener);
- }
+ /**
+ * Allows to stream SSE events from horizon.
+ * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
+ * This mode will keep the connection to horizon open and horizon will continue to return
+ * responses as ledgers close.
+ *
+ * @param listener {@link EventListener} implementation with {@link AccountResponse} type
+ * @return ServerSentEvent object, so you can close() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return new StreamHandler(new TypeToken() {
+ })
+ .handleStream(this.buildUri(), (EventListener) listener);
+ }
- /**
- * Build and execute request. Warning! {@link AccountResponse}s in {@link Page} will contain only keypair field.
- * @return {@link Page} of {@link AccountResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
+ /**
+ * Build and execute request. Warning! {@link AccountResponse}s in {@link Page} will contain only keypair field.
+ *
+ * @return {@link Page} of {@link AccountResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
- @Override
- public AccountsRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
+ @Override
+ public AccountsRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
- @Override
- public AccountsRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
+ @Override
+ public AccountsRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
+<<<<<<< HEAD
@Override
public AccountsRequestBuilder order(Order direction) {
super.order(direction);
return this;
}
+
+=======
+ @Override
+ public AccountsRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
+>>>>>>> master
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/EffectsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/EffectsRequestBuilder.java
index 2be1cdb5..3c3fd5bc 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/EffectsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/EffectsRequestBuilder.java
@@ -1,121 +1,133 @@
package kin.base.requests;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.reflect.TypeToken;
import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.KeyPair;
import kin.base.responses.Page;
import kin.base.responses.effects.EffectResponse;
import okhttp3.OkHttpClient;
+import static kin.base.Util.checkNotNull;
+
/**
* Builds requests connected to effects.
*/
public class EffectsRequestBuilder extends RequestBuilder {
- public EffectsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "effects");
- }
-
- /**
- * Builds request to GET /accounts/{account}/effects
- * @see Effects for Account
- * @param account Account for which to get effects
- */
- public EffectsRequestBuilder forAccount(KeyPair account) {
- account = checkNotNull(account, "account cannot be null");
- this.setSegments("accounts", account.getAccountId(), "effects");
- return this;
- }
-
- /**
- * Builds request to GET /ledgers/{ledgerSeq}/effects
- * @see Effects for Ledger
- * @param ledgerSeq Ledger for which to get effects
- */
- public EffectsRequestBuilder forLedger(long ledgerSeq) {
- this.setSegments("ledgers", String.valueOf(ledgerSeq), "effects");
- return this;
- }
-
- /**
- * Builds request to GET /transactions/{transactionId}/effects
- * @see Effect for Transaction
- * @param transactionId Transaction ID for which to get effects
- */
- public EffectsRequestBuilder forTransaction(String transactionId) {
- transactionId = checkNotNull(transactionId, "transactionId cannot be null");
- this.setSegments("transactions", transactionId, "effects");
- return this;
- }
-
- /**
- * Builds request to GET /operation/{operationId}/effects
- * @see Effect for Operation
- * @param operationId Operation ID for which to get effects
- */
- public EffectsRequestBuilder forOperation(long operationId) {
- this.setSegments("operations", String.valueOf(operationId), "effects");
- return this;
- }
-
- /**
- * Requests specific uri and returns {@link Page} of {@link EffectResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link EffectResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Allows to stream SSE events from horizon.
- * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
- * This mode will keep the connection to horizon open and horizon will continue to return
- * responses as ledgers close.
- * @see Server-Sent Events
- * @see Response Format documentation
- * @param listener {@link EventListener} implementation with {@link EffectResponse} type
- * @return ServerSentEvent object, so you can close() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListener listener) {
- return new StreamHandler<>(new TypeToken() {})
- .handleStream(this.buildUri(),listener);
- }
-
- /**
- * Build and execute request.
- * @return {@link Page} of {@link EffectResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
-
- @Override
- public EffectsRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
-
- @Override
- public EffectsRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
-
- @Override
- public EffectsRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ public EffectsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "effects");
+ }
+
+ /**
+ * Builds request to GET /accounts/{account}/effects
+ *
+ * @param account Account for which to get effects
+ * @see Effects for Account
+ */
+ public EffectsRequestBuilder forAccount(KeyPair account) {
+ account = checkNotNull(account, "account cannot be null");
+ this.setSegments("accounts", account.getAccountId(), "effects");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /ledgers/{ledgerSeq}/effects
+ *
+ * @param ledgerSeq Ledger for which to get effects
+ * @see Effects for Ledger
+ */
+ public EffectsRequestBuilder forLedger(long ledgerSeq) {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq), "effects");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /transactions/{transactionId}/effects
+ *
+ * @param transactionId Transaction ID for which to get effects
+ * @see Effect for Transaction
+ */
+ public EffectsRequestBuilder forTransaction(String transactionId) {
+ transactionId = checkNotNull(transactionId, "transactionId cannot be null");
+ this.setSegments("transactions", transactionId, "effects");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /operation/{operationId}/effects
+ *
+ * @param operationId Operation ID for which to get effects
+ * @see Effect for Operation
+ */
+ public EffectsRequestBuilder forOperation(long operationId) {
+ this.setSegments("operations", String.valueOf(operationId), "effects");
+ return this;
+ }
+
+ /**
+ * Requests specific uri and returns {@link Page} of {@link EffectResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link EffectResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Allows to stream SSE events from horizon.
+ * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
+ * This mode will keep the connection to horizon open and horizon will continue to return
+ * responses as ledgers close.
+ *
+ * @param listener {@link EventListener} implementation with {@link EffectResponse} type
+ * @return ServerSentEvent object, so you can close() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return new StreamHandler(new TypeToken() {
+ })
+ .handleStream(this.buildUri(), (EventListener) listener);
+ }
+
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link EffectResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
+
+ @Override
+ public EffectsRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
+
+ @Override
+ public EffectsRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
+
+ @Override
+ public EffectsRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/EventListener.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/EventListener.java
index b6540e2c..397f8a1b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/EventListener.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/EventListener.java
@@ -4,9 +4,10 @@
* This interface is used in {@link RequestBuilder} classes stream method.
*/
public interface EventListener {
- /**
- * This method will be called when new event is sent by a server.
- * @param object object deserialized from the event data
- */
- void onEvent(T object);
+ /**
+ * This method will be called when new event is sent by a server.
+ *
+ * @param object object deserialized from the event data
+ */
+ void onEvent(T object);
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/LedgersRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/LedgersRequestBuilder.java
index b7038673..75c4b140 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/LedgersRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/LedgersRequestBuilder.java
@@ -2,8 +2,10 @@
import com.google.gson.reflect.TypeToken;
import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.responses.LedgerResponse;
import kin.base.responses.Page;
import okhttp3.OkHttpClient;
@@ -13,86 +15,96 @@
*/
public class LedgersRequestBuilder extends RequestBuilder {
- public LedgersRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "ledgers");
- }
+ public LedgersRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "ledgers");
+ }
+
+ /**
+ * Requests specific uri and returns {@link LedgerResponse}.
+ * This method is helpful for getting the links.
+ *
+ * @throws IOException
+ */
+ public LedgerResponse ledger(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
- /**
- * Requests specific uri and returns {@link LedgerResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
- */
- public LedgerResponse ledger(URI uri) throws IOException {
- TypeToken type = new TypeToken() {};
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
+ /**
+ * Requests GET /ledgers/{ledgerSeq}
+ *
+ * @param ledgerSeq Ledger to fetch
+ * @throws IOException
+ * @see Ledger Details
+ */
+ public LedgerResponse ledger(long ledgerSeq) throws IOException {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq));
+ return this.ledger(this.buildUri());
+ }
- /**
- * Requests GET /ledgers/{ledgerSeq}
- * @see Ledger Details
- * @param ledgerSeq Ledger to fetch
- * @throws IOException
- */
- public LedgerResponse ledger(long ledgerSeq) throws IOException {
- this.setSegments("ledgers", String.valueOf(ledgerSeq));
- return this.ledger(this.buildUri());
- }
+ /**
+ * Requests specific uri and returns {@link Page} of {@link LedgerResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link LedgerResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
- /**
- * Requests specific uri and returns {@link Page} of {@link LedgerResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link LedgerResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
- /**
- * Allows to stream SSE events from horizon.
- * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
- * This mode will keep the connection to horizon open and horizon will continue to return
- * responses as ledgers close.
- * @see Server-Sent Events
- * @see Response Format documentation
- * @param listener {@link EventListener} implementation with {@link LedgerResponse} type
- * @return ServerSentEvent object, so you can close() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListener listener) {
- return new StreamHandler<>(new TypeToken() {})
- .handleStream(this.buildUri(),listener);
- }
+ /**
+ * Allows to stream SSE events from horizon.
+ * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
+ * This mode will keep the connection to horizon open and horizon will continue to return
+ * responses as ledgers close.
+ *
+ * @param listener {@link EventListener} implementation with {@link LedgerResponse} type
+ * @return ServerSentEvent object, so you can close() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return new StreamHandler(new TypeToken() {
+ })
+ .handleStream(this.buildUri(), (EventListener) listener);
+ }
- /**
- * Build and execute request.
- * @return {@link Page} of {@link LedgerResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link LedgerResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
- @Override
- public LedgersRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
+ @Override
+ public LedgersRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
- @Override
- public LedgersRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
+ @Override
+ public LedgersRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
- @Override
- public LedgersRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ @Override
+ public LedgersRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/OffersRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/OffersRequestBuilder.java
index 93009ef3..7aa188de 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/OffersRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/OffersRequestBuilder.java
@@ -1,74 +1,86 @@
package kin.base.requests;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.reflect.TypeToken;
+import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.KeyPair;
import kin.base.responses.OfferResponse;
import kin.base.responses.Page;
import okhttp3.OkHttpClient;
+import static kin.base.Util.checkNotNull;
+
/**
* Builds requests connected to offers.
*/
public class OffersRequestBuilder extends RequestBuilder {
- public OffersRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "offers");
- }
+ public OffersRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "offers");
+ }
+
+ /**
+ * Builds request to GET /accounts/{account}/offers
+ *
+ * @param account Account for which to get offers
+ * @see Offers for Account
+ */
+ public OffersRequestBuilder forAccount(KeyPair account) {
+ account = checkNotNull(account, "account cannot be null");
+ this.setSegments("accounts", account.getAccountId(), "offers");
+ return this;
+ }
- /**
- * Builds request to GET /accounts/{account}/offers
- * @see Offers for Account
- * @param account Account for which to get offers
- */
- public OffersRequestBuilder forAccount(KeyPair account) {
- account = checkNotNull(account, "account cannot be null");
- this.setSegments("accounts", account.getAccountId(), "offers");
- return this;
- }
+ /**
+ * Requests specific uri and returns {@link Page} of {@link OfferResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link OfferResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
- /**
- * Requests specific uri and returns {@link Page} of {@link OfferResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link OfferResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link OfferResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
- /**
- * Build and execute request.
- * @return {@link Page} of {@link OfferResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
+ @Override
+ public OffersRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
- @Override
- public OffersRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
+ @Override
+ public OffersRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
- @Override
- public OffersRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
+ @Override
+ public OffersRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
- @Override
- public OffersRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return null;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/OperationsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/OperationsRequestBuilder.java
index 8259abda..9acb061b 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/OperationsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/OperationsRequestBuilder.java
@@ -1,118 +1,135 @@
package kin.base.requests;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.reflect.TypeToken;
+import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.KeyPair;
import kin.base.responses.Page;
import kin.base.responses.operations.OperationResponse;
import okhttp3.OkHttpClient;
+import static kin.base.Util.checkNotNull;
+
/**
* Builds requests connected to operations.
*/
public class OperationsRequestBuilder extends RequestBuilder {
- public OperationsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "operations");
- }
-
- /**
- * Requests specific uri and returns {@link OperationResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
- */
- public OperationResponse operation(URI uri) throws IOException {
- TypeToken type = new TypeToken() {};
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Requests GET /operations/{operationId}
- * @see Operation Details
- * @param operationId Operation to fetch
- * @throws IOException
- */
- public OperationResponse operation(long operationId) throws IOException {
- this.setSegments("operation", String.valueOf(operationId));
- return this.operation(this.buildUri());
- }
-
- /**
- * Builds request to GET /accounts/{account}/operations
- * @see Operations for Account
- * @param account Account for which to get operations
- */
- public OperationsRequestBuilder forAccount(KeyPair account) {
- account = checkNotNull(account, "account cannot be null");
- this.setSegments("accounts", account.getAccountId(), "operations");
- return this;
- }
-
- /**
- * Builds request to GET /ledgers/{ledgerSeq}/operations
- * @see Operations for Ledger
- * @param ledgerSeq Ledger for which to get operations
- */
- public OperationsRequestBuilder forLedger(long ledgerSeq) {
- this.setSegments("ledgers", String.valueOf(ledgerSeq), "operations");
- return this;
- }
-
- /**
- * Builds request to GET /transactions/{transactionId}/operations
- * @see Operations for Transaction
- * @param transactionId Transaction ID for which to get operations
- */
- public OperationsRequestBuilder forTransaction(String transactionId) {
- transactionId = checkNotNull(transactionId, "transactionId cannot be null");
- this.setSegments("transactions", transactionId, "operations");
- return this;
- }
-
- /**
- * Requests specific uri and returns {@link Page} of {@link OperationResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link OperationResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient,
- type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Build and execute request.
- * @return {@link Page} of {@link OperationResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
-
- @Override
- public OperationsRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
-
- @Override
- public OperationsRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
-
- @Override
- public OperationsRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ public OperationsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "operations");
+ }
+
+ /**
+ * Requests specific uri and returns {@link OperationResponse}.
+ * This method is helpful for getting the links.
+ *
+ * @throws IOException
+ */
+ public OperationResponse operation(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Requests GET /operations/{operationId}
+ *
+ * @param operationId Operation to fetch
+ * @throws IOException
+ * @see Operation Details
+ */
+ public OperationResponse operation(long operationId) throws IOException {
+ this.setSegments("operation", String.valueOf(operationId));
+ return this.operation(this.buildUri());
+ }
+
+ /**
+ * Builds request to GET /accounts/{account}/operations
+ *
+ * @param account Account for which to get operations
+ * @see Operations for Account
+ */
+ public OperationsRequestBuilder forAccount(KeyPair account) {
+ account = checkNotNull(account, "account cannot be null");
+ this.setSegments("accounts", account.getAccountId(), "operations");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /ledgers/{ledgerSeq}/operations
+ *
+ * @param ledgerSeq Ledger for which to get operations
+ * @see Operations for Ledger
+ */
+ public OperationsRequestBuilder forLedger(long ledgerSeq) {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq), "operations");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /transactions/{transactionId}/operations
+ *
+ * @param transactionId Transaction ID for which to get operations
+ * @see Operations for Transaction
+ */
+ public OperationsRequestBuilder forTransaction(String transactionId) {
+ transactionId = checkNotNull(transactionId, "transactionId cannot be null");
+ this.setSegments("transactions", transactionId, "operations");
+ return this;
+ }
+
+ /**
+ * Requests specific uri and returns {@link Page} of {@link OperationResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link OperationResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient,
+ type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link OperationResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
+
+ @Override
+ public OperationsRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
+
+ @Override
+ public OperationsRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
+
+ @Override
+ public OperationsRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
+
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return null;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/OrderBookRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/OrderBookRequestBuilder.java
index 705aac8e..ec366d75 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/OrderBookRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/OrderBookRequestBuilder.java
@@ -1,8 +1,11 @@
package kin.base.requests;
import com.google.gson.reflect.TypeToken;
+import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.Asset;
import kin.base.AssetTypeCreditAlphaNum;
import kin.base.responses.OrderBookResponse;
@@ -13,53 +16,59 @@
*/
public class OrderBookRequestBuilder extends RequestBuilder {
- public OrderBookRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "order_book");
- }
+ public OrderBookRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "order_book");
+ }
- public OrderBookRequestBuilder buyingAsset(Asset asset) {
- uriBuilder.appendQueryParameter("buying_asset_type", asset.getType());
- if (asset instanceof AssetTypeCreditAlphaNum) {
- AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
- uriBuilder.appendQueryParameter("buying_asset_code", creditAlphaNumAsset.getCode());
- uriBuilder.appendQueryParameter("buying_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ public OrderBookRequestBuilder buyingAsset(Asset asset) {
+ uriBuilder.addEncodedQueryParameter("buying_asset_type", asset.getType());
+ if (asset instanceof AssetTypeCreditAlphaNum) {
+ AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
+ uriBuilder.addEncodedQueryParameter("buying_asset_code", creditAlphaNumAsset.getCode());
+ uriBuilder.addEncodedQueryParameter("buying_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ }
+ return this;
}
- return this;
- }
-
- public OrderBookRequestBuilder sellingAsset(Asset asset) {
- uriBuilder.appendQueryParameter("selling_asset_type", asset.getType());
- if (asset instanceof AssetTypeCreditAlphaNum) {
- AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
- uriBuilder.appendQueryParameter("selling_asset_code", creditAlphaNumAsset.getCode());
- uriBuilder.appendQueryParameter("selling_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+
+ public OrderBookRequestBuilder sellingAsset(Asset asset) {
+ uriBuilder.addEncodedQueryParameter("selling_asset_type", asset.getType());
+ if (asset instanceof AssetTypeCreditAlphaNum) {
+ AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
+ uriBuilder.addEncodedQueryParameter("selling_asset_code", creditAlphaNumAsset.getCode());
+ uriBuilder.addEncodedQueryParameter("selling_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ }
+ return this;
}
- return this;
- }
- public static OrderBookResponse execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken() {};
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
+ public static OrderBookResponse execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
- public OrderBookResponse execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
+ public OrderBookResponse execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
- @Override
- public RequestBuilder cursor(String cursor) {
- throw new RuntimeException("Not implemented yet.");
- }
+ @Override
+ public RequestBuilder cursor(String cursor) {
+ throw new RuntimeException("Not implemented yet.");
+ }
- @Override
- public RequestBuilder limit(int number) {
- throw new RuntimeException("Not implemented yet.");
- }
+ @Override
+ public RequestBuilder limit(int number) {
+ throw new RuntimeException("Not implemented yet.");
+ }
- @Override
- public RequestBuilder order(Order direction) {
- throw new RuntimeException("Not implemented yet.");
- }
+ @Override
+ public RequestBuilder order(Order direction) {
+ throw new RuntimeException("Not implemented yet.");
+ }
+
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return null;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/PathsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/PathsRequestBuilder.java
index 26782519..ab011eb1 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/PathsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/PathsRequestBuilder.java
@@ -1,8 +1,11 @@
package kin.base.requests;
import com.google.gson.reflect.TypeToken;
+import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.Asset;
import kin.base.AssetTypeCreditAlphaNum;
import kin.base.KeyPair;
@@ -15,51 +18,57 @@
*/
public class PathsRequestBuilder extends RequestBuilder {
- public PathsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "paths");
- }
+ public PathsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "paths");
+ }
+
+ public PathsRequestBuilder destinationAccount(KeyPair account) {
+ uriBuilder.addEncodedQueryParameter("destination_account", account.getAccountId());
+ return this;
+ }
- public PathsRequestBuilder destinationAccount(KeyPair account) {
- uriBuilder.appendQueryParameter("destination_account", account.getAccountId());
- return this;
- }
+ public PathsRequestBuilder sourceAccount(KeyPair account) {
+ uriBuilder.addEncodedQueryParameter("source_account", account.getAccountId());
+ return this;
+ }
- public PathsRequestBuilder sourceAccount(KeyPair account) {
- uriBuilder.appendQueryParameter("source_account", account.getAccountId());
- return this;
- }
+ public PathsRequestBuilder destinationAmount(String amount) {
+ uriBuilder.addEncodedQueryParameter("destination_amount", amount);
+ return this;
+ }
- public PathsRequestBuilder destinationAmount(String amount) {
- uriBuilder.appendQueryParameter("destination_amount", amount);
- return this;
- }
+ public PathsRequestBuilder destinationAsset(Asset asset) {
+ uriBuilder.addEncodedQueryParameter("destination_asset_type", asset.getType());
+ if (asset instanceof AssetTypeCreditAlphaNum) {
+ AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
+ uriBuilder.addEncodedQueryParameter("destination_asset_code", creditAlphaNumAsset.getCode());
+ uriBuilder.addEncodedQueryParameter("destination_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ }
+ return this;
+ }
- public PathsRequestBuilder destinationAsset(Asset asset) {
- uriBuilder.appendQueryParameter("destination_asset_type", asset.getType());
- if (asset instanceof AssetTypeCreditAlphaNum) {
- AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
- uriBuilder.appendQueryParameter("destination_asset_code", creditAlphaNumAsset.getCode());
- uriBuilder.appendQueryParameter("destination_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ /**
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
}
- return this;
- }
- /**
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
+ /**
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
- /**
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return null;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/PaymentsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/PaymentsRequestBuilder.java
index 638970f7..d71101a3 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/PaymentsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/PaymentsRequestBuilder.java
@@ -1,113 +1,124 @@
package kin.base.requests;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.reflect.TypeToken;
import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.KeyPair;
import kin.base.responses.Page;
import kin.base.responses.operations.OperationResponse;
import okhttp3.OkHttpClient;
+import static kin.base.Util.checkNotNull;
+
/**
* Builds requests connected to payments.
*/
public class PaymentsRequestBuilder extends RequestBuilder {
- public PaymentsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "payments");
- }
-
- /**
- * Builds request to GET /accounts/{account}/payments
- * @see Payments for Account
- * @param account Account for which to get payments
- */
- public PaymentsRequestBuilder forAccount(KeyPair account) {
- account = checkNotNull(account, "account cannot be null");
- this.setSegments("accounts", account.getAccountId(), "payments");
- return this;
- }
-
- /**
- * Builds request to GET /ledgers/{ledgerSeq}/payments
- * @see Payments for Ledger
- * @param ledgerSeq Ledger for which to get payments
- */
- public PaymentsRequestBuilder forLedger(long ledgerSeq) {
- this.setSegments("ledgers", String.valueOf(ledgerSeq), "payments");
- return this;
- }
-
- /**
- * Builds request to GET /transactions/{transactionId}/payments
- * @see Payments for Transaction
- * @param transactionId Transaction ID for which to get payments
- */
- public PaymentsRequestBuilder forTransaction(String transactionId) {
- transactionId = checkNotNull(transactionId, "transactionId cannot be null");
- this.setSegments("transactions", transactionId, "payments");
- return this;
- }
-
- /**
- * Requests specific uri and returns {@link Page} of {@link OperationResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link OperationResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient,
- type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Allows to stream SSE events from horizon.
- * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
- * This mode will keep the connection to horizon open and horizon will continue to return
- * responses as ledgers close.
- * @see Server-Sent Events
- * @see Response Format documentation
- * @param listener {@link EventListener} implementation with {@link OperationResponse} type
- * @return ServerSentEvent object, so you can close() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListener listener) {
- return new StreamHandler<>(new TypeToken() {})
- .handleStream(this.buildUri(),listener);
- }
-
- /**
- * Build and execute request.
- * @return {@link Page} of {@link OperationResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
-
- @Override
- public PaymentsRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
-
- @Override
- public PaymentsRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
-
- @Override
- public PaymentsRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ public PaymentsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "payments");
+ }
+
+ /**
+ * Builds request to GET /accounts/{account}/payments
+ *
+ * @param account Account for which to get payments
+ * @see Payments for Account
+ */
+ public PaymentsRequestBuilder forAccount(KeyPair account) {
+ account = checkNotNull(account, "account cannot be null");
+ this.setSegments("accounts", account.getAccountId(), "payments");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /ledgers/{ledgerSeq}/payments
+ *
+ * @param ledgerSeq Ledger for which to get payments
+ * @see Payments for Ledger
+ */
+ public PaymentsRequestBuilder forLedger(long ledgerSeq) {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq), "payments");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /transactions/{transactionId}/payments
+ *
+ * @param transactionId Transaction ID for which to get payments
+ * @see Payments for Transaction
+ */
+ public PaymentsRequestBuilder forTransaction(String transactionId) {
+ transactionId = checkNotNull(transactionId, "transactionId cannot be null");
+ this.setSegments("transactions", transactionId, "payments");
+ return this;
+ }
+
+ /**
+ * Requests specific uri and returns {@link Page} of {@link OperationResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link OperationResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient,
+ type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Allows to stream SSE events from horizon.
+ * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
+ * This mode will keep the connection to horizon open and horizon will continue to return
+ * responses as ledgers close.
+ *
+ * @param listener {@link EventListener} implementation with {@link OperationResponse} type
+ * @return ServerSentEvent object, so you can close() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return new StreamHandler(new TypeToken() {
+ })
+ .handleStream(this.buildUri(), (EventListener) listener);
+ }
+
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link OperationResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
+
+ @Override
+ public PaymentsRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
+
+ @Override
+ public PaymentsRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
+
+ @Override
+ public PaymentsRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/RequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/RequestBuilder.java
index 4f4ea7bd..2600c51f 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/RequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/RequestBuilder.java
@@ -1,8 +1,13 @@
package kin.base.requests;
-import android.net.Uri;
+import com.here.oksse.ServerSentEvent;
+
import java.net.URI;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+
+import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
/**
@@ -10,91 +15,89 @@
*/
public abstract class RequestBuilder {
- protected final Uri.Builder uriBuilder;
- protected final OkHttpClient httpClient;
- private final ArrayList segments;
- private boolean segmentsAdded;
+ protected final HttpUrl.Builder uriBuilder;
+ protected final OkHttpClient httpClient;
+ private final ArrayList segments;
+ private boolean segmentsAdded;
+
+ RequestBuilder(OkHttpClient httpClient, URI serverURI, String... defaultSegments) {
+ uriBuilder = HttpUrl.parse(serverURI.toString()).newBuilder();
+ segments = new ArrayList();
+ segments.addAll(Arrays.asList(defaultSegments));
+ this.httpClient = httpClient;
+ }
+
+ protected RequestBuilder setSegments(String... segments) {
+ if (segmentsAdded) {
+ throw new RuntimeException("URL segments have been already added.");
+ }
+ segmentsAdded = true;
+ // Remove default segments
+ this.segments.clear();
+ Collections.addAll(this.segments, segments);
- RequestBuilder(OkHttpClient httpClient, URI serverURI, String defaultSegment) {
- uriBuilder = Uri.parse(serverURI.toString()).buildUpon();
- segments = new ArrayList();
- if (defaultSegment != null) {
- this.setSegments(defaultSegment);
+ return this;
}
- segmentsAdded = false; // Allow overwriting segments
- this.httpClient = httpClient;
- }
- protected RequestBuilder setSegments(String... segments) {
- if (segmentsAdded) {
- throw new RuntimeException("URL segments have been already added.");
+ /**
+ * Sets cursor parameter on the request.
+ * A cursor is a value that points to a specific location in a collection of resources.
+ * The cursor attribute itself is an opaque value meaning that users should not try to parse it.
+ *
+ * @param cursor
+ * @see Page documentation
+ */
+ public RequestBuilder cursor(String cursor) {
+ uriBuilder.addQueryParameter("cursor", cursor);
+ return this;
}
- segmentsAdded = true;
- // Remove default segments
- this.segments.clear();
- for (String segment : segments) {
- this.segments.add(segment);
+ /**
+ * Sets limit parameter on the request.
+ * It defines maximum number of records to return.
+ * For range and default values check documentation of the endpoint requested.
+ *
+ * @param number maxium number of records to return
+ */
+ public RequestBuilder limit(int number) {
+ uriBuilder.addQueryParameter("limit", String.valueOf(number));
+ return this;
}
- return this;
- }
-
- /**
- * Sets cursor parameter on the request.
- * A cursor is a value that points to a specific location in a collection of resources.
- * The cursor attribute itself is an opaque value meaning that users should not try to parse it.
- * @see Page documentation
- * @param cursor
- */
- public RequestBuilder cursor(String cursor) {
- uriBuilder.appendQueryParameter("cursor", cursor);
- return this;
- }
-
- /**
- * Sets limit parameter on the request.
- * It defines maximum number of records to return.
- * For range and default values check documentation of the endpoint requested.
- * @param number maxium number of records to return
- */
- public RequestBuilder limit(int number) {
- uriBuilder.appendQueryParameter("limit", String.valueOf(number));
- return this;
- }
-
- /**
- * Sets order parameter on the request.
- * @param direction {@link kin.base.requests.RequestBuilder.Order}
- */
- public RequestBuilder order(Order direction) {
- uriBuilder.appendQueryParameter("order", direction.getValue());
- return this;
- }
-
- URI buildUri() {
- if (segments.size() > 0) {
- String path = "";
- for (String segment : segments) {
- path += "/"+segment;
- }
- uriBuilder.path(path);
+ /**
+ * Sets order parameter on the request.
+ *
+ * @param direction {@link kin.base.requests.RequestBuilder.Order}
+ */
+ public RequestBuilder order(Order direction) {
+ uriBuilder.addQueryParameter("order", direction.getValue());
+ return this;
}
- return URI.create(uriBuilder.build().toString());
- }
-
- /**
- * Represents possible order parameter values.
- */
- public enum Order {
- ASC("asc"),
- DESC("desc");
- private final String value;
- Order(String value) {
- this.value = value;
+
+ URI buildUri() {
+ for (String segment : segments) {
+ uriBuilder.addPathSegment(segment);
+ }
+ segments.clear();
+ return URI.create(uriBuilder.build().toString());
}
- public String getValue() {
- return value;
+
+ /**
+ * Represents possible order parameter values.
+ */
+ public enum Order {
+ ASC("asc"),
+ DESC("desc");
+ private final String value;
+
+ Order(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
}
- }
+
+ abstract public ServerSentEvent stream(final EventListener listener);
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/ResponseHandler.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/ResponseHandler.java
index f5da86c5..8d02004e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/ResponseHandler.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/ResponseHandler.java
@@ -1,8 +1,10 @@
package kin.base.requests;
import com.google.gson.reflect.TypeToken;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.responses.ClientProtocolException;
import kin.base.responses.GsonSingleton;
import kin.base.responses.HttpResponseException;
@@ -29,11 +31,11 @@ public ResponseHandler(OkHttpClient httpClient, TypeToken type) {
public T handleGetRequest(final URI uri) throws IOException {
return handleResponse(httpClient.newCall(
- new Request.Builder()
- .url(uri.toString())
- .build()
+ new Request.Builder()
+ .url(uri.toString())
+ .build()
)
- .execute());
+ .execute());
}
public T handleResponse(final okhttp3.Response response) throws IOException, TooManyRequestsException {
@@ -68,9 +70,9 @@ public T handleResponse(final okhttp3.Response response) throws IOException, Too
T object = GsonSingleton.getInstance().fromJson(responseBody.string(), type.getType());
if (object instanceof Response) {
((Response) object).setHeaders(
- response.header("X-Ratelimit-Limit"),
- response.header("X-Ratelimit-Remaining"),
- response.header("X-Ratelimit-Reset")
+ response.header("X-Ratelimit-Limit"),
+ response.header("X-Ratelimit-Remaining"),
+ response.header("X-Ratelimit-Reset")
);
}
return object;
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/StreamHandler.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/StreamHandler.java
index d7677985..b54c649e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/StreamHandler.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/StreamHandler.java
@@ -5,77 +5,79 @@
import com.google.gson.reflect.TypeToken;
import com.here.oksse.OkSse;
import com.here.oksse.ServerSentEvent;
+
import java.net.URI;
+
import kin.base.responses.GsonSingleton;
import okhttp3.Request;
public class StreamHandler {
- private static final String OPEN_MESSAGE_DATA = "\"hello\""; //opening message contains "hello" string
- private TypeToken type;
- private OkSse okSse = new OkSse();
-
- /**
- * "Generics on a type are typically erased at runtime, except when the type is compiled with the
- * generic parameter bound. In that case, the compiler inserts the generic type information into
- * the compiled class. In other cases, that is not possible."
- * More info: http://stackoverflow.com/a/14506181
- *
- * @param type
- */
- public StreamHandler(TypeToken type) {
- this.type = type;
- }
-
- public ServerSentEvent handleStream(final URI uri, final EventListener listener) {
- Request request = new Request.Builder()
- .url(uri.toString())
- .build();
-
- return okSse.newServerSentEvent(request, new ServerSentEvent.Listener() {
- @Override
- public void onOpen(ServerSentEvent sse, okhttp3.Response response) {
- }
-
- @Override
- public void onMessage(ServerSentEvent sse, String id, String event, String data) {
- if (OPEN_MESSAGE_DATA.equals(data)) {
- return;
- }
- try {
- T object = GsonSingleton.getInstance().fromJson(data, type.getType());
- if (object != null) {
- listener.onEvent(object);
- }
- } catch (JsonParseException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onComment(ServerSentEvent sse, String comment) {
- }
-
- @Override
- public boolean onRetryTime(ServerSentEvent sse, long milliseconds) {
- return true;
- }
-
- @Override
- public boolean onRetryError(ServerSentEvent sse, Throwable throwable, okhttp3.Response response) {
- return true;
- }
-
- @Override
- public void onClosed(ServerSentEvent sse) {
- }
-
- @Override
- public Request onPreRetry(ServerSentEvent sse, Request originalRequest) {
- return originalRequest;
- }
- });
- }
+ private static final String OPEN_MESSAGE_DATA = "\"hello\""; //opening message contains "hello" string
+ private TypeToken type;
+ private OkSse okSse = new OkSse();
+
+ /**
+ * "Generics on a type are typically erased at runtime, except when the type is compiled with the
+ * generic parameter bound. In that case, the compiler inserts the generic type information into
+ * the compiled class. In other cases, that is not possible."
+ * More info: http://stackoverflow.com/a/14506181
+ *
+ * @param type
+ */
+ public StreamHandler(TypeToken type) {
+ this.type = type;
+ }
+
+ public ServerSentEvent handleStream(final URI uri, final EventListener listener) {
+ Request request = new Request.Builder()
+ .url(uri.toString())
+ .build();
+
+ return okSse.newServerSentEvent(request, new ServerSentEvent.Listener() {
+ @Override
+ public void onOpen(ServerSentEvent sse, okhttp3.Response response) {
+ }
+
+ @Override
+ public void onMessage(ServerSentEvent sse, String id, String event, String data) {
+ if (OPEN_MESSAGE_DATA.equals(data)) {
+ return;
+ }
+ try {
+ T object = GsonSingleton.getInstance().fromJson(data, type.getType());
+ if (object != null) {
+ listener.onEvent(object);
+ }
+ } catch (JsonParseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onComment(ServerSentEvent sse, String comment) {
+ }
+
+ @Override
+ public boolean onRetryTime(ServerSentEvent sse, long milliseconds) {
+ return true;
+ }
+
+ @Override
+ public boolean onRetryError(ServerSentEvent sse, Throwable throwable, okhttp3.Response response) {
+ return true;
+ }
+
+ @Override
+ public void onClosed(ServerSentEvent sse) {
+ }
+
+ @Override
+ public Request onPreRetry(ServerSentEvent sse, Request originalRequest) {
+ return originalRequest;
+ }
+ });
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/TooManyRequestsException.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/TooManyRequestsException.java
index 3d1c35b7..b70bd439 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/TooManyRequestsException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/TooManyRequestsException.java
@@ -2,20 +2,21 @@
/**
* Exception thrown when too many requests were sent to the Horizon server.
+ *
* @see Rate Limiting
*/
public class TooManyRequestsException extends RuntimeException {
- private int retryAfter;
+ private int retryAfter;
- public TooManyRequestsException(int retryAfter) {
- super("The rate limit for the requesting IP address is over its alloted limit.");
- this.retryAfter = retryAfter;
- }
+ public TooManyRequestsException(int retryAfter) {
+ super("The rate limit for the requesting IP address is over its alloted limit.");
+ this.retryAfter = retryAfter;
+ }
- /**
- * Returns number of seconds a client should wait before sending requests again.
- */
- public int getRetryAfter() {
- return retryAfter;
- }
+ /**
+ * Returns number of seconds a client should wait before sending requests again.
+ */
+ public int getRetryAfter() {
+ return retryAfter;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/TradesRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/TradesRequestBuilder.java
index 882e3903..95536182 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/TradesRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/TradesRequestBuilder.java
@@ -1,8 +1,11 @@
package kin.base.requests;
import com.google.gson.reflect.TypeToken;
+import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.Asset;
import kin.base.AssetTypeCreditAlphaNum;
import kin.base.responses.TradeResponse;
@@ -14,31 +17,32 @@
public class TradesRequestBuilder extends RequestBuilder {
public TradesRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "order_book/trades");
+ super(httpClient, serverURI, "order_book", "trades");
}
public TradesRequestBuilder buyingAsset(Asset asset) {
- uriBuilder.appendQueryParameter("buying_asset_type", asset.getType());
+ uriBuilder.addEncodedQueryParameter("buying_asset_type", asset.getType());
if (asset instanceof AssetTypeCreditAlphaNum) {
AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
- uriBuilder.appendQueryParameter("buying_asset_code", creditAlphaNumAsset.getCode());
- uriBuilder.appendQueryParameter("buying_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ uriBuilder.addEncodedQueryParameter("buying_asset_code", creditAlphaNumAsset.getCode());
+ uriBuilder.addEncodedQueryParameter("buying_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
}
return this;
}
public TradesRequestBuilder sellingAsset(Asset asset) {
- uriBuilder.appendQueryParameter("selling_asset_type", asset.getType());
+ uriBuilder.addEncodedQueryParameter("selling_asset_type", asset.getType());
if (asset instanceof AssetTypeCreditAlphaNum) {
AssetTypeCreditAlphaNum creditAlphaNumAsset = (AssetTypeCreditAlphaNum) asset;
- uriBuilder.appendQueryParameter("selling_asset_code", creditAlphaNumAsset.getCode());
- uriBuilder.appendQueryParameter("selling_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
+ uriBuilder.addEncodedQueryParameter("selling_asset_code", creditAlphaNumAsset.getCode());
+ uriBuilder.addEncodedQueryParameter("selling_asset_issuer", creditAlphaNumAsset.getIssuer().getAccountId());
}
return this;
}
public static TradeResponse execute(OkHttpClient httpClient, URI uri) throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken() {};
+ TypeToken type = new TypeToken() {
+ };
ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
return responseHandler.handleGetRequest(uri);
}
@@ -46,4 +50,9 @@ public static TradeResponse execute(OkHttpClient httpClient, URI uri) throws IOE
public TradeResponse execute() throws IOException, TooManyRequestsException {
return this.execute(httpClient, this.buildUri());
}
+
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return null;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/requests/TransactionsRequestBuilder.java b/kin-sdk/kin-base/src/main/java/kin/base/requests/TransactionsRequestBuilder.java
index 2641f7d6..093fdb90 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/requests/TransactionsRequestBuilder.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/requests/TransactionsRequestBuilder.java
@@ -1,126 +1,140 @@
package kin.base.requests;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.reflect.TypeToken;
import com.here.oksse.ServerSentEvent;
+
import java.io.IOException;
import java.net.URI;
+
import kin.base.KeyPair;
import kin.base.responses.Page;
import kin.base.responses.TransactionResponse;
import okhttp3.OkHttpClient;
+import static kin.base.Util.checkNotNull;
+
/**
* Builds requests connected to transactions.
*/
public class TransactionsRequestBuilder extends RequestBuilder {
- private final OkHttpClient httpClient;
-
- public TransactionsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
- super(httpClient, serverURI, "transactions");
- this.httpClient = httpClient;
- }
-
- /**
- * Requests specific uri and returns {@link TransactionResponse}.
- * This method is helpful for getting the links.
- * @throws IOException
- */
- public TransactionResponse transaction(URI uri) throws IOException {
- TypeToken type = new TypeToken() {};
- ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Requests GET /transactions/{transactionId}
- * @see Transaction Details
- * @param transactionId Transaction to fetch
- * @throws IOException
- */
- public TransactionResponse transaction(String transactionId) throws IOException {
- this.setSegments("transactions", transactionId);
- return this.transaction(this.buildUri());
- }
-
- /**
- * Builds request to GET /accounts/{account}/transactions
- * @see Transactions for Account
- * @param account Account for which to get transactions
- */
- public TransactionsRequestBuilder forAccount(KeyPair account) {
- account = checkNotNull(account, "account cannot be null");
- this.setSegments("accounts", account.getAccountId(), "transactions");
- return this;
- }
-
- /**
- * Builds request to GET /ledgers/{ledgerSeq}/transactions
- * @see Transactions for Ledger
- * @param ledgerSeq Ledger for which to get transactions
- */
- public TransactionsRequestBuilder forLedger(long ledgerSeq) {
- this.setSegments("ledgers", String.valueOf(ledgerSeq), "transactions");
- return this;
- }
-
- /**
- * Requests specific uri and returns {@link Page} of {@link TransactionResponse}.
- * This method is helpful for getting the next set of results.
- * @return {@link Page} of {@link TransactionResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public static Page execute(OkHttpClient httpClient, URI uri)
- throws IOException, TooManyRequestsException {
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(
- httpClient, type);
- return responseHandler.handleGetRequest(uri);
- }
-
- /**
- * Allows to stream SSE events from horizon.
- * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
- * This mode will keep the connection to horizon open and horizon will continue to return
- * responses as ledgers close.
- * @see Server-Sent Events
- * @see Response Format documentation
- * @param listener {@link EventListener} implementation with {@link TransactionResponse} type
- * @return ServerSentEvent object, so you can close() connection when not needed anymore
- */
- public ServerSentEvent stream(final EventListener listener) {
- return new StreamHandler<>(new TypeToken() {})
- .handleStream(this.buildUri(),listener);
- }
-
- /**
- * Build and execute request.
- * @return {@link Page} of {@link TransactionResponse}
- * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
- * @throws IOException
- */
- public Page execute() throws IOException, TooManyRequestsException {
- return this.execute(httpClient, this.buildUri());
- }
-
- @Override
- public TransactionsRequestBuilder cursor(String token) {
- super.cursor(token);
- return this;
- }
-
- @Override
- public TransactionsRequestBuilder limit(int number) {
- super.limit(number);
- return this;
- }
-
- @Override
- public TransactionsRequestBuilder order(Order direction) {
- super.order(direction);
- return this;
- }
+ private final OkHttpClient httpClient;
+
+ public TransactionsRequestBuilder(OkHttpClient httpClient, URI serverURI) {
+ super(httpClient, serverURI, "transactions");
+ this.httpClient = httpClient;
+ }
+
+ /**
+ * Requests specific uri and returns {@link TransactionResponse}.
+ * This method is helpful for getting the links.
+ *
+ * @throws IOException
+ */
+ public TransactionResponse transaction(URI uri) throws IOException {
+ TypeToken type = new TypeToken() {
+ };
+ ResponseHandler responseHandler = new ResponseHandler(httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+ /**
+ * Requests GET /transactions/{transactionId}
+ *
+ * @param transactionId Transaction to fetch
+ * @throws IOException
+ * @see Transaction Details
+ */
+ public TransactionResponse transaction(String transactionId) throws IOException {
+ this.setSegments("transactions", transactionId);
+ return this.transaction(this.buildUri());
+ }
+
+ /**
+ * Builds request to GET /accounts/{account}/transactions
+ *
+ * @param account Account for which to get transactions
+ * @see Transactions for Account
+ */
+ public TransactionsRequestBuilder forAccount(KeyPair account) {
+ account = checkNotNull(account, "account cannot be null");
+ this.setSegments("accounts", account.getAccountId(), "transactions");
+ return this;
+ }
+
+ /**
+ * Builds request to GET /ledgers/{ledgerSeq}/transactions
+ *
+ * @param ledgerSeq Ledger for which to get transactions
+ * @see Transactions for Ledger
+ */
+ public TransactionsRequestBuilder forLedger(long ledgerSeq) {
+ this.setSegments("ledgers", String.valueOf(ledgerSeq), "transactions");
+ return this;
+ }
+
+ /**
+ * Requests specific uri and returns {@link Page} of {@link TransactionResponse}.
+ * This method is helpful for getting the next set of results.
+ *
+ * @return {@link Page} of {@link TransactionResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public static Page execute(OkHttpClient httpClient, URI uri)
+ throws IOException, TooManyRequestsException {
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(
+ httpClient, type);
+ return responseHandler.handleGetRequest(uri);
+ }
+
+
+ /**
+ * Allows to stream SSE events from horizon.
+ * Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
+ * This mode will keep the connection to horizon open and horizon will continue to return
+ * responses as ledgers close.
+ *
+ * @param listener {@link EventListener} implementation with {@link TransactionResponse} type
+ * @return ServerSentEvent object, so you can close() connection when not needed anymore
+ * @see Server-Sent Events
+ * @see Response Format documentation
+ */
+ @Override
+ public ServerSentEvent stream(EventListener listener) {
+ return new StreamHandler(new TypeToken() {
+ })
+ .handleStream(this.buildUri(), (EventListener) listener);
+ }
+
+ /**
+ * Build and execute request.
+ *
+ * @return {@link Page} of {@link TransactionResponse}
+ * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
+ * @throws IOException
+ */
+ public Page execute() throws IOException, TooManyRequestsException {
+ return this.execute(httpClient, this.buildUri());
+ }
+
+ @Override
+ public TransactionsRequestBuilder cursor(String token) {
+ super.cursor(token);
+ return this;
+ }
+
+ @Override
+ public TransactionsRequestBuilder limit(int number) {
+ super.limit(number);
+ return this;
+ }
+
+ @Override
+ public TransactionsRequestBuilder order(Order direction) {
+ super.order(direction);
+ return this;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
index efc8c831..b75b4337 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/AccountResponse.java
@@ -1,21 +1,28 @@
package kin.base.responses;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.annotations.SerializedName;
+<<<<<<< HEAD
+import java.util.Map;
+=======
+
+>>>>>>> master
import kin.base.Asset;
import kin.base.AssetTypeNative;
import kin.base.KeyPair;
import kin.base.Server;
import kin.base.TransactionBuilderAccount;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents account response.
+ *
* @see Account documentation
* @see kin.base.requests.AccountsRequestBuilder
* @see Server#accounts()
*/
public class AccountResponse extends Response implements TransactionBuilderAccount {
+<<<<<<< HEAD
@SerializedName("account_id") /* KeyPairTypeAdapter used */
private KeyPair keypair;
@SerializedName("sequence")
@@ -38,6 +45,8 @@ public class AccountResponse extends Response implements TransactionBuilderAccou
private Signer[] signers;
@SerializedName("_links")
private Links links;
+ @SerializedName("data")
+ private Map data;
AccountResponse(KeyPair keypair) {
this.keypair = keypair;
@@ -100,6 +109,10 @@ public Signer[] getSigners() {
return signers;
}
+ public Map getData() {
+ return data;
+ }
+
/**
* Represents account thresholds.
*/
@@ -115,16 +128,46 @@ public static class Thresholds {
this.lowThreshold = lowThreshold;
this.medThreshold = medThreshold;
this.highThreshold = highThreshold;
+=======
+ @SerializedName("account_id") /* KeyPairTypeAdapter used */
+ private KeyPair keypair;
+ @SerializedName("sequence")
+ private Long sequenceNumber;
+ @SerializedName("paging_token")
+ private String pagingToken;
+ @SerializedName("subentry_count")
+ private Integer subentryCount;
+ @SerializedName("inflation_destination")
+ private String inflationDestination;
+ @SerializedName("home_domain")
+ private String homeDomain;
+ @SerializedName("thresholds")
+ private Thresholds thresholds;
+ @SerializedName("flags")
+ private Flags flags;
+ @SerializedName("balances")
+ private Balance[] balances;
+ @SerializedName("signers")
+ private Signer[] signers;
+ @SerializedName("_links")
+ private Links links;
+
+ AccountResponse(KeyPair keypair) {
+ this.keypair = keypair;
+>>>>>>> master
}
- public int getLowThreshold() {
- return lowThreshold;
+ public AccountResponse(KeyPair keypair, Long sequenceNumber) {
+ this.keypair = keypair;
+ this.sequenceNumber = sequenceNumber;
}
- public int getMedThreshold() {
- return medThreshold;
+ @Override
+ public KeyPair getKeypair() {
+ return keypair;
}
+<<<<<<< HEAD
public int getHighThreshold() {
return highThreshold;
}
@@ -138,19 +181,33 @@ public static class Flags {
private final boolean authRequired;
@SerializedName("auth_revocable")
private final boolean authRevocable;
+ @SerializedName("auth_immutable")
+ private final boolean authImmutable;
- Flags(boolean authRequired, boolean authRevocable) {
+ Flags(boolean authRequired, boolean authRevocable, boolean authImmutable) {
this.authRequired = authRequired;
this.authRevocable = authRevocable;
+ this.authImmutable = authImmutable;
+=======
+ @Override
+ public Long getSequenceNumber() {
+ return sequenceNumber;
+>>>>>>> master
}
- public boolean getAuthRequired() {
- return authRequired;
+ @Override
+ public Long getIncrementedSequenceNumber() {
+ return new Long(sequenceNumber + 1);
}
+<<<<<<< HEAD
public boolean getAuthRevocable() {
return authRevocable;
}
+
+ public boolean getAuthImmutable() {
+ return authImmutable;
+ }
}
/**
@@ -174,105 +231,218 @@ public static class Balance {
this.limit = limit;
this.assetCode = assetCode;
this.assetIssuer = assetIssuer;
+=======
+ @Override
+ public void incrementSequenceNumber() {
+ sequenceNumber++;
+>>>>>>> master
}
- public Asset getAsset() {
- if (assetType.equals("native")) {
- return new AssetTypeNative();
- } else {
- return Asset.createNonNativeAsset(assetCode, getAssetIssuer());
- }
- }
-
- public String getAssetType() {
- return assetType;
+ public String getPagingToken() {
+ return pagingToken;
}
- public String getAssetCode() {
- return assetCode;
+ public Integer getSubentryCount() {
+ return subentryCount;
}
- public KeyPair getAssetIssuer() {
- return KeyPair.fromAccountId(assetIssuer);
+ public String getInflationDestination() {
+ return inflationDestination;
}
- public String getBalance() {
- return balance;
+ public String getHomeDomain() {
+ return homeDomain;
}
- public String getLimit() {
- return limit;
+ public Thresholds getThresholds() {
+ return thresholds;
}
- }
- /**
- * Represents account signers.
- */
- public static class Signer {
- @SerializedName("public_key")
- private final String accountId;
- @SerializedName("weight")
- private final int weight;
-
- Signer(String accountId, int weight) {
- this.accountId = checkNotNull(accountId, "accountId cannot be null");
- this.weight = checkNotNull(weight, "weight cannot be null");
+ public Flags getFlags() {
+ return flags;
}
- public String getAccountId() {
- return accountId;
+ public Balance[] getBalances() {
+ return balances;
}
- public int getWeight() {
- return weight;
+ public Signer[] getSigners() {
+ return signers;
}
- }
- public Links getLinks() {
- return links;
- }
-
- /**
- * Links connected to account.
- */
- public static class Links {
- @SerializedName("effects")
- private final Link effects;
- @SerializedName("offers")
- private final Link offers;
- @SerializedName("operations")
- private final Link operations;
- @SerializedName("self")
- private final Link self;
- @SerializedName("transactions")
- private final Link transactions;
-
- Links(Link effects, Link offers, Link operations, Link self, Link transactions) {
- this.effects = effects;
- this.offers = offers;
- this.operations = operations;
- this.self = self;
- this.transactions = transactions;
+ /**
+ * Represents account thresholds.
+ */
+ public static class Thresholds {
+ @SerializedName("low_threshold")
+ private final int lowThreshold;
+ @SerializedName("med_threshold")
+ private final int medThreshold;
+ @SerializedName("high_threshold")
+ private final int highThreshold;
+
+ Thresholds(int lowThreshold, int medThreshold, int highThreshold) {
+ this.lowThreshold = lowThreshold;
+ this.medThreshold = medThreshold;
+ this.highThreshold = highThreshold;
+ }
+
+ public int getLowThreshold() {
+ return lowThreshold;
+ }
+
+ public int getMedThreshold() {
+ return medThreshold;
+ }
+
+ public int getHighThreshold() {
+ return highThreshold;
+ }
}
- public Link getEffects() {
- return effects;
+ /**
+ * Represents account flags.
+ */
+ public static class Flags {
+ @SerializedName("auth_required")
+ private final boolean authRequired;
+ @SerializedName("auth_revocable")
+ private final boolean authRevocable;
+
+ Flags(boolean authRequired, boolean authRevocable) {
+ this.authRequired = authRequired;
+ this.authRevocable = authRevocable;
+ }
+
+ public boolean getAuthRequired() {
+ return authRequired;
+ }
+
+ public boolean getAuthRevocable() {
+ return authRevocable;
+ }
}
- public Link getOffers() {
- return offers;
+ /**
+ * Represents account balance.
+ */
+ public static class Balance {
+ @SerializedName("asset_type")
+ private final String assetType;
+ @SerializedName("asset_code")
+ private final String assetCode;
+ @SerializedName("asset_issuer")
+ private final String assetIssuer;
+ @SerializedName("limit")
+ private final String limit;
+ @SerializedName("balance")
+ private final String balance;
+
+ Balance(String assetType, String assetCode, String assetIssuer, String balance, String limit) {
+ this.assetType = checkNotNull(assetType, "assertType cannot be null");
+ this.balance = checkNotNull(balance, "balance cannot be null");
+ this.limit = limit;
+ this.assetCode = assetCode;
+ this.assetIssuer = assetIssuer;
+ }
+
+ public Asset getAsset() {
+ if (assetType.equals("native")) {
+ return new AssetTypeNative();
+ } else {
+ return Asset.createNonNativeAsset(assetCode, getAssetIssuer());
+ }
+ }
+
+ public String getAssetType() {
+ return assetType;
+ }
+
+ public String getAssetCode() {
+ return assetCode;
+ }
+
+ public KeyPair getAssetIssuer() {
+ return KeyPair.fromAccountId(assetIssuer);
+ }
+
+ public String getBalance() {
+ return balance;
+ }
+
+ public String getLimit() {
+ return limit;
+ }
}
- public Link getOperations() {
- return operations;
+ /**
+ * Represents account signers.
+ */
+ public static class Signer {
+ @SerializedName("public_key")
+ private final String accountId;
+ @SerializedName("weight")
+ private final int weight;
+
+ Signer(String accountId, int weight) {
+ this.accountId = checkNotNull(accountId, "accountId cannot be null");
+ this.weight = checkNotNull(weight, "weight cannot be null");
+ }
+
+ public String getAccountId() {
+ return accountId;
+ }
+
+ public int getWeight() {
+ return weight;
+ }
}
- public Link getSelf() {
- return self;
+ public Links getLinks() {
+ return links;
}
- public Link getTransactions() {
- return transactions;
+ /**
+ * Links connected to account.
+ */
+ public static class Links {
+ @SerializedName("effects")
+ private final Link effects;
+ @SerializedName("offers")
+ private final Link offers;
+ @SerializedName("operations")
+ private final Link operations;
+ @SerializedName("self")
+ private final Link self;
+ @SerializedName("transactions")
+ private final Link transactions;
+
+ Links(Link effects, Link offers, Link operations, Link self, Link transactions) {
+ this.effects = effects;
+ this.offers = offers;
+ this.operations = operations;
+ this.self = self;
+ this.transactions = transactions;
+ }
+
+ public Link getEffects() {
+ return effects;
+ }
+
+ public Link getOffers() {
+ return offers;
+ }
+
+ public Link getOperations() {
+ return operations;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
+
+ public Link getTransactions() {
+ return transactions;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/AggregatedBalanceResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/AggregatedBalanceResponse.java
new file mode 100644
index 00000000..de4f1597
--- /dev/null
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/AggregatedBalanceResponse.java
@@ -0,0 +1,91 @@
+package kin.base.responses;
+
+import com.google.gson.annotations.SerializedName;
+import kin.base.Server;
+
+/**
+ * Represents account aggregated balance response.
+ *
+ * @see Account
+ * documentation
+ * @see Server#accounts()
+ */
+public class AggregatedBalanceResponse extends Response {
+
+ @SerializedName("_embedded")
+ private Records records;
+ @SerializedName("_links")
+ private Links links;
+
+ public AggregatedBalance getAggregatedBalance() {
+ return records.getAggregateBalances()[0];
+ }
+
+ /**
+ * Represents records of aggregated balances.
+ */
+ public static class Records {
+
+ @SerializedName("records")
+ private AggregatedBalance[] aggregatedBalances;
+
+ public AggregatedBalance[] getAggregateBalances() {
+ return aggregatedBalances;
+ }
+ }
+
+ /**
+ * Represents account aggregated balance.
+ */
+ public static class AggregatedBalance {
+
+ @SerializedName("account_id")
+ private String accountId;
+ @SerializedName("aggregate_balance")
+ private String aggregateBalance;
+
+ public String getAccountId() {
+ return accountId;
+ }
+
+ public String getAggregateBalance() {
+ return aggregateBalance;
+ }
+ }
+
+ public Links getLinks() {
+ return links;
+ }
+
+ /**
+ * Links connected to account.
+ */
+ public static class Links {
+
+ @SerializedName("self")
+ private final Link self;
+ @SerializedName("next")
+ private final Link next;
+ @SerializedName("prev")
+ private final Link prev;
+
+ Links(Link self, Link next, Link prev) {
+ this.self = self;
+ this.next = next;
+ this.prev = prev;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
+
+ public Link getNext() {
+ return next;
+ }
+
+ public Link getPrev() {
+ return prev;
+ }
+ }
+}
+
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/AssetDeserializer.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/AssetDeserializer.java
index 842aa7ff..bc942c13 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/AssetDeserializer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/AssetDeserializer.java
@@ -4,21 +4,23 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
+
import java.lang.reflect.Type;
+
import kin.base.Asset;
import kin.base.AssetTypeNative;
import kin.base.KeyPair;
class AssetDeserializer implements JsonDeserializer {
- @Override
- public Asset deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- String type = json.getAsJsonObject().get("asset_type").getAsString();
- if (type.equals("native")) {
- return new AssetTypeNative();
- } else {
- String code = json.getAsJsonObject().get("asset_code").getAsString();
- String issuer = json.getAsJsonObject().get("asset_issuer").getAsString();
- return Asset.createNonNativeAsset(code, KeyPair.fromAccountId(issuer));
+ @Override
+ public Asset deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ String type = json.getAsJsonObject().get("asset_type").getAsString();
+ if (type.equals("native")) {
+ return new AssetTypeNative();
+ } else {
+ String code = json.getAsJsonObject().get("asset_code").getAsString();
+ String issuer = json.getAsJsonObject().get("asset_issuer").getAsString();
+ return Asset.createNonNativeAsset(code, KeyPair.fromAccountId(issuer));
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/ClientProtocolException.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/ClientProtocolException.java
index 33029c27..a18a01f1 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/ClientProtocolException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/ClientProtocolException.java
@@ -4,22 +4,22 @@
public class ClientProtocolException extends IOException {
- public ClientProtocolException() {
- super();
- }
+ public ClientProtocolException() {
+ super();
+ }
- public ClientProtocolException(String s) {
- super(s);
- }
+ public ClientProtocolException(String s) {
+ super(s);
+ }
- public ClientProtocolException(Throwable cause) {
- initCause(cause);
- }
+ public ClientProtocolException(Throwable cause) {
+ initCause(cause);
+ }
- public ClientProtocolException(String message, Throwable cause) {
- super(message);
- initCause(cause);
- }
+ public ClientProtocolException(String message, Throwable cause) {
+ super(message);
+ initCause(cause);
+ }
-}
\ No newline at end of file
+}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/ControlledAccountsResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/ControlledAccountsResponse.java
new file mode 100644
index 00000000..5bcc9515
--- /dev/null
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/ControlledAccountsResponse.java
@@ -0,0 +1,92 @@
+package kin.base.responses;
+
+import com.google.gson.annotations.SerializedName;
+import kin.base.Server;
+
+/**
+ * Represents controlled account response.
+ *
+ * @see Account
+ * documentation
+ * @see Server#accounts()
+ */
+public class ControlledAccountsResponse {
+
+
+ @SerializedName("_embedded")
+ private Records records;
+ @SerializedName("_links")
+ private Links links;
+
+ public ControlledAccount[] getControlledAccounts() {
+ return records.getControlledAccounts();
+ }
+
+ /**
+ * Represents records of aggregated balances.
+ */
+ public static class Records {
+
+ @SerializedName("records")
+ private ControlledAccount[] controlledAccounts;
+
+ public ControlledAccount[] getControlledAccounts() {
+ return controlledAccounts;
+ }
+ }
+
+ /**
+ * Represents account aggregated balance.
+ */
+ public static class ControlledAccount {
+
+ @SerializedName("account_id")
+ private String accountId;
+ @SerializedName("balance")
+ private String balance;
+
+ public String getAccountId() {
+ return accountId;
+ }
+
+ public String getBalance() {
+ return balance;
+ }
+ }
+
+ public Links getLinks() {
+ return links;
+ }
+
+ /**
+ * Links connected to account.
+ */
+ public static class Links {
+
+ @SerializedName("self")
+ private final Link self;
+ @SerializedName("next")
+ private final Link next;
+ @SerializedName("prev")
+ private final Link prev;
+
+ Links(Link self, Link next, Link prev) {
+ this.self = self;
+ this.next = next;
+ this.prev = prev;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
+
+ public Link getNext() {
+ return next;
+ }
+
+ public Link getPrev() {
+ return prev;
+ }
+ }
+}
+
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/EffectDeserializer.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/EffectDeserializer.java
index aacfac15..2c1e898e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/EffectDeserializer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/EffectDeserializer.java
@@ -6,7 +6,9 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
+
import java.lang.reflect.Type;
+
import kin.base.KeyPair;
import kin.base.responses.effects.AccountCreatedEffectResponse;
import kin.base.responses.effects.AccountCreditedEffectResponse;
@@ -30,59 +32,59 @@
import kin.base.responses.effects.TrustlineUpdatedEffectResponse;
class EffectDeserializer implements JsonDeserializer {
- @Override
- public EffectResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- // Create new Gson object with adapters needed in Operation
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
- .create();
+ @Override
+ public EffectResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ // Create new Gson object with adapters needed in Operation
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
+ .create();
- int type = json.getAsJsonObject().get("type_i").getAsInt();
- switch (type) {
- // Account effects
- case 0:
- return gson.fromJson(json, AccountCreatedEffectResponse.class);
- case 1:
- return gson.fromJson(json, AccountRemovedEffectResponse.class);
- case 2:
- return gson.fromJson(json, AccountCreditedEffectResponse.class);
- case 3:
- return gson.fromJson(json, AccountDebitedEffectResponse.class);
- case 4:
- return gson.fromJson(json, AccountThresholdsUpdatedEffectResponse.class);
- case 5:
- return gson.fromJson(json, AccountHomeDomainUpdatedEffectResponse.class);
- case 6:
- return gson.fromJson(json, AccountFlagsUpdatedEffectResponse.class);
- // Signer effects
- case 10:
- return gson.fromJson(json, SignerCreatedEffectResponse.class);
- case 11:
- return gson.fromJson(json, SignerRemovedEffectResponse.class);
- case 12:
- return gson.fromJson(json, SignerUpdatedEffectResponse.class);
- // Trustline effects
- case 20:
- return gson.fromJson(json, TrustlineCreatedEffectResponse.class);
- case 21:
- return gson.fromJson(json, TrustlineRemovedEffectResponse.class);
- case 22:
- return gson.fromJson(json, TrustlineUpdatedEffectResponse.class);
- case 23:
- return gson.fromJson(json, TrustlineAuthorizedEffectResponse.class);
- case 24:
- return gson.fromJson(json, TrustlineDeauthorizedEffectResponse.class);
- // Trading effects
- case 30:
- return gson.fromJson(json, OfferCreatedEffectResponse.class);
- case 31:
- return gson.fromJson(json, OfferRemovedEffectResponse.class);
- case 32:
- return gson.fromJson(json, OfferUpdatedEffectResponse.class);
- case 33:
- return gson.fromJson(json, TradeEffectResponse.class);
- default:
- throw new RuntimeException("Invalid operation type");
+ int type = json.getAsJsonObject().get("type_i").getAsInt();
+ switch (type) {
+ // Account effects
+ case 0:
+ return gson.fromJson(json, AccountCreatedEffectResponse.class);
+ case 1:
+ return gson.fromJson(json, AccountRemovedEffectResponse.class);
+ case 2:
+ return gson.fromJson(json, AccountCreditedEffectResponse.class);
+ case 3:
+ return gson.fromJson(json, AccountDebitedEffectResponse.class);
+ case 4:
+ return gson.fromJson(json, AccountThresholdsUpdatedEffectResponse.class);
+ case 5:
+ return gson.fromJson(json, AccountHomeDomainUpdatedEffectResponse.class);
+ case 6:
+ return gson.fromJson(json, AccountFlagsUpdatedEffectResponse.class);
+ // Signer effects
+ case 10:
+ return gson.fromJson(json, SignerCreatedEffectResponse.class);
+ case 11:
+ return gson.fromJson(json, SignerRemovedEffectResponse.class);
+ case 12:
+ return gson.fromJson(json, SignerUpdatedEffectResponse.class);
+ // Trustline effects
+ case 20:
+ return gson.fromJson(json, TrustlineCreatedEffectResponse.class);
+ case 21:
+ return gson.fromJson(json, TrustlineRemovedEffectResponse.class);
+ case 22:
+ return gson.fromJson(json, TrustlineUpdatedEffectResponse.class);
+ case 23:
+ return gson.fromJson(json, TrustlineAuthorizedEffectResponse.class);
+ case 24:
+ return gson.fromJson(json, TrustlineDeauthorizedEffectResponse.class);
+ // Trading effects
+ case 30:
+ return gson.fromJson(json, OfferCreatedEffectResponse.class);
+ case 31:
+ return gson.fromJson(json, OfferRemovedEffectResponse.class);
+ case 32:
+ return gson.fromJson(json, OfferUpdatedEffectResponse.class);
+ case 33:
+ return gson.fromJson(json, TradeEffectResponse.class);
+ default:
+ throw new RuntimeException("Invalid operation type");
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/GsonSingleton.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/GsonSingleton.java
index 6892d59c..f9a36c33 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/GsonSingleton.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/GsonSingleton.java
@@ -3,44 +3,54 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
+
import kin.base.Asset;
import kin.base.KeyPair;
import kin.base.responses.effects.EffectResponse;
import kin.base.responses.operations.OperationResponse;
public class GsonSingleton {
- private static Gson instance = null;
+ private static Gson instance = null;
- protected GsonSingleton() {}
+ protected GsonSingleton() {
+ }
- public static Gson getInstance() {
- if (instance == null) {
- TypeToken accountPageType = new TypeToken>() {};
- TypeToken effectPageType = new TypeToken>() {};
- TypeToken ledgerPageType = new TypeToken>() {};
- TypeToken offerPageType = new TypeToken>() {};
- TypeToken operationPageType = new TypeToken>() {};
- TypeToken pathPageType = new TypeToken>() {};
- TypeToken tradePageType = new TypeToken>() {};
- TypeToken transactionPageType = new TypeToken>() {};
+ public static Gson getInstance() {
+ if (instance == null) {
+ TypeToken accountPageType = new TypeToken>() {
+ };
+ TypeToken effectPageType = new TypeToken>() {
+ };
+ TypeToken ledgerPageType = new TypeToken>() {
+ };
+ TypeToken offerPageType = new TypeToken>() {
+ };
+ TypeToken operationPageType = new TypeToken>() {
+ };
+ TypeToken pathPageType = new TypeToken>() {
+ };
+ TypeToken tradePageType = new TypeToken>() {
+ };
+ TypeToken transactionPageType = new TypeToken>() {
+ };
- instance = new GsonBuilder()
- .registerTypeAdapter(Asset.class, new AssetDeserializer())
- .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
- .registerTypeAdapter(OperationResponse.class, new OperationDeserializer())
- .registerTypeAdapter(EffectResponse.class, new EffectDeserializer())
- .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer())
- .registerTypeAdapter(accountPageType.getType(), new PageDeserializer(accountPageType))
- .registerTypeAdapter(effectPageType.getType(), new PageDeserializer(effectPageType))
- .registerTypeAdapter(ledgerPageType.getType(), new PageDeserializer(ledgerPageType))
- .registerTypeAdapter(offerPageType.getType(), new PageDeserializer(offerPageType))
- .registerTypeAdapter(operationPageType.getType(), new PageDeserializer(operationPageType))
- .registerTypeAdapter(pathPageType.getType(), new PageDeserializer(pathPageType))
- .registerTypeAdapter(tradePageType.getType(), new PageDeserializer(tradePageType))
- .registerTypeAdapter(transactionPageType.getType(), new PageDeserializer(transactionPageType))
- .create();
+ instance = new GsonBuilder()
+ .registerTypeAdapter(Asset.class, new AssetDeserializer())
+ .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
+ .registerTypeAdapter(OperationResponse.class, new OperationDeserializer())
+ .registerTypeAdapter(EffectResponse.class, new EffectDeserializer())
+ .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer())
+ .registerTypeAdapter(accountPageType.getType(), new PageDeserializer(accountPageType))
+ .registerTypeAdapter(effectPageType.getType(), new PageDeserializer(effectPageType))
+ .registerTypeAdapter(ledgerPageType.getType(), new PageDeserializer(ledgerPageType))
+ .registerTypeAdapter(offerPageType.getType(), new PageDeserializer(offerPageType))
+ .registerTypeAdapter(operationPageType.getType(), new PageDeserializer(operationPageType))
+ .registerTypeAdapter(pathPageType.getType(), new PageDeserializer(pathPageType))
+ .registerTypeAdapter(tradePageType.getType(), new PageDeserializer(tradePageType))
+ .registerTypeAdapter(transactionPageType.getType(), new PageDeserializer(transactionPageType))
+ .create();
+ }
+ return instance;
}
- return instance;
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/HttpResponseException.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/HttpResponseException.java
index c3ab344b..d9124e3a 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/HttpResponseException.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/HttpResponseException.java
@@ -3,14 +3,15 @@
public class HttpResponseException extends ClientProtocolException {
- private final int statusCode;
+ private final int statusCode;
- public HttpResponseException(int statusCode, final String s) {
- super(s);
- this.statusCode = statusCode;
- }
- public int getStatusCode() {
- return this.statusCode;
- }
+ public HttpResponseException(int statusCode, final String s) {
+ super(s);
+ this.statusCode = statusCode;
+ }
+
+ public int getStatusCode() {
+ return this.statusCode;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/KeyPairTypeAdapter.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/KeyPairTypeAdapter.java
index 9c7d742a..23373c92 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/KeyPairTypeAdapter.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/KeyPairTypeAdapter.java
@@ -3,17 +3,19 @@
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
+
import java.io.IOException;
+
import kin.base.KeyPair;
class KeyPairTypeAdapter extends TypeAdapter {
- @Override
- public void write(JsonWriter out, KeyPair value) throws IOException {
- // Don't need this.
- }
+ @Override
+ public void write(JsonWriter out, KeyPair value) throws IOException {
+ // Don't need this.
+ }
- @Override
- public KeyPair read(JsonReader in) throws IOException {
- return KeyPair.fromAccountId(in.nextString());
- }
+ @Override
+ public KeyPair read(JsonReader in) throws IOException {
+ return KeyPair.fromAccountId(in.nextString());
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/LedgerResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/LedgerResponse.java
index 42fb41f9..c45251e2 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/LedgerResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/LedgerResponse.java
@@ -1,144 +1,146 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import kin.base.Server;
/**
* Represents ledger response.
+ *
* @see Ledger documentation
* @see kin.base.requests.LedgersRequestBuilder
* @see Server#ledgers()
*/
public class LedgerResponse extends Response {
- @SerializedName("sequence")
- private final Long sequence;
- @SerializedName("hash")
- private final String hash;
- @SerializedName("paging_token")
- private final String pagingToken;
- @SerializedName("prev_hash")
- private final String prevHash;
- @SerializedName("transaction_count")
- private final Integer transactionCount;
- @SerializedName("operation_count")
- private final Integer operationCount;
- @SerializedName("closed_at")
- private final String closedAt;
- @SerializedName("total_coins")
- private final String totalCoins;
- @SerializedName("fee_pool")
- private final String feePool;
- @SerializedName("base_fee_in_stroops")
- private final Long baseFee;
- @SerializedName("base_reserve")
- private final String baseReserve;
- @SerializedName("max_tx_set_size")
- private final Integer maxTxSetSize;
- @SerializedName("_links")
- private final Links links;
-
- LedgerResponse(Long sequence, String hash, String pagingToken, String prevHash, Integer transactionCount, Integer operationCount, String closedAt, String totalCoins, String feePool, Long baseFee, String baseReserve, Integer maxTxSetSize, Links links) {
- this.sequence = sequence;
- this.hash = hash;
- this.pagingToken = pagingToken;
- this.prevHash = prevHash;
- this.transactionCount = transactionCount;
- this.operationCount = operationCount;
- this.closedAt = closedAt;
- this.totalCoins = totalCoins;
- this.feePool = feePool;
- this.baseFee = baseFee;
- this.baseReserve = baseReserve;
- this.maxTxSetSize = maxTxSetSize;
- this.links = links;
- }
-
- public Long getSequence() {
- return sequence;
- }
-
- public String getHash() {
- return hash;
- }
-
- public String getPagingToken() {
- return pagingToken;
- }
-
- public String getPrevHash() {
- return prevHash;
- }
-
- public Integer getTransactionCount() {
- return transactionCount;
- }
-
- public Integer getOperationCount() {
- return operationCount;
- }
-
- public String getClosedAt() {
- return closedAt;
- }
-
- public String getTotalCoins() {
- return totalCoins;
- }
-
- public String getFeePool() {
- return feePool;
- }
-
- public Long getBaseFee() {
- return baseFee;
- }
-
- public String getBaseReserve() {
- return baseReserve;
- }
-
- public Integer getMaxTxSetSize() {
- return maxTxSetSize;
- }
-
- public Links getLinks() {
- return links;
- }
-
- /**
- * Links connected to ledger.
- */
- public static class Links {
- @SerializedName("effects")
- private final Link effects;
- @SerializedName("operations")
- private final Link operations;
- @SerializedName("self")
- private final Link self;
- @SerializedName("transactions")
- private final Link transactions;
-
- Links(Link effects, Link operations, Link self, Link transactions) {
- this.effects = effects;
- this.operations = operations;
- this.self = self;
- this.transactions = transactions;
+ @SerializedName("sequence")
+ private final Long sequence;
+ @SerializedName("hash")
+ private final String hash;
+ @SerializedName("paging_token")
+ private final String pagingToken;
+ @SerializedName("prev_hash")
+ private final String prevHash;
+ @SerializedName("transaction_count")
+ private final Integer transactionCount;
+ @SerializedName("operation_count")
+ private final Integer operationCount;
+ @SerializedName("closed_at")
+ private final String closedAt;
+ @SerializedName("total_coins")
+ private final String totalCoins;
+ @SerializedName("fee_pool")
+ private final String feePool;
+ @SerializedName("base_fee_in_stroops")
+ private final Long baseFee;
+ @SerializedName("base_reserve")
+ private final String baseReserve;
+ @SerializedName("max_tx_set_size")
+ private final Integer maxTxSetSize;
+ @SerializedName("_links")
+ private final Links links;
+
+ LedgerResponse(Long sequence, String hash, String pagingToken, String prevHash, Integer transactionCount, Integer operationCount, String closedAt, String totalCoins, String feePool, Long baseFee, String baseReserve, Integer maxTxSetSize, Links links) {
+ this.sequence = sequence;
+ this.hash = hash;
+ this.pagingToken = pagingToken;
+ this.prevHash = prevHash;
+ this.transactionCount = transactionCount;
+ this.operationCount = operationCount;
+ this.closedAt = closedAt;
+ this.totalCoins = totalCoins;
+ this.feePool = feePool;
+ this.baseFee = baseFee;
+ this.baseReserve = baseReserve;
+ this.maxTxSetSize = maxTxSetSize;
+ this.links = links;
+ }
+
+ public Long getSequence() {
+ return sequence;
+ }
+
+ public String getHash() {
+ return hash;
+ }
+
+ public String getPagingToken() {
+ return pagingToken;
+ }
+
+ public String getPrevHash() {
+ return prevHash;
+ }
+
+ public Integer getTransactionCount() {
+ return transactionCount;
+ }
+
+ public Integer getOperationCount() {
+ return operationCount;
+ }
+
+ public String getClosedAt() {
+ return closedAt;
+ }
+
+ public String getTotalCoins() {
+ return totalCoins;
+ }
+
+ public String getFeePool() {
+ return feePool;
+ }
+
+ public Long getBaseFee() {
+ return baseFee;
}
- public Link getEffects() {
- return effects;
+ public String getBaseReserve() {
+ return baseReserve;
}
- public Link getOperations() {
- return operations;
+ public Integer getMaxTxSetSize() {
+ return maxTxSetSize;
}
- public Link getSelf() {
- return self;
+ public Links getLinks() {
+ return links;
}
- public Link getTransactions() {
- return transactions;
+ /**
+ * Links connected to ledger.
+ */
+ public static class Links {
+ @SerializedName("effects")
+ private final Link effects;
+ @SerializedName("operations")
+ private final Link operations;
+ @SerializedName("self")
+ private final Link self;
+ @SerializedName("transactions")
+ private final Link transactions;
+
+ Links(Link effects, Link operations, Link self, Link transactions) {
+ this.effects = effects;
+ this.operations = operations;
+ this.self = self;
+ this.transactions = transactions;
+ }
+
+ public Link getEffects() {
+ return effects;
+ }
+
+ public Link getOperations() {
+ return operations;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
+
+ public Link getTransactions() {
+ return transactions;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/Link.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/Link.java
index b448ce98..f219264d 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/Link.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/Link.java
@@ -1,6 +1,7 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import java.net.URI;
import java.net.URISyntaxException;
@@ -8,31 +9,31 @@
* Represents links in responses.
*/
public class Link {
- @SerializedName("href")
- private final String href;
- @SerializedName("templated")
- private final boolean templated;
+ @SerializedName("href")
+ private final String href;
+ @SerializedName("templated")
+ private final boolean templated;
- Link(String href, boolean templated) {
- this.href = href;
- this.templated = templated;
- }
+ Link(String href, boolean templated) {
+ this.href = href;
+ this.templated = templated;
+ }
- public String getHref() {
- // TODO templated
- return href;
- }
+ public String getHref() {
+ // TODO templated
+ return href;
+ }
- public URI getUri() {
- // TODO templated
- try {
- return new URI(href);
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
+ public URI getUri() {
+ // TODO templated
+ try {
+ return new URI(href);
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
}
- }
- public boolean isTemplated() {
- return templated;
- }
+ public boolean isTemplated() {
+ return templated;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/OfferResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/OfferResponse.java
index ade6197b..eb55f2c1 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/OfferResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/OfferResponse.java
@@ -1,97 +1,99 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import kin.base.Asset;
import kin.base.KeyPair;
import kin.base.Server;
/**
* Represents offer response.
+ *
* @see Offer documentation
* @see kin.base.requests.OffersRequestBuilder
* @see Server#offers()
*/
public class OfferResponse extends Response {
- @SerializedName("id")
- private final Long id;
- @SerializedName("paging_token")
- private final String pagingToken;
- @SerializedName("seller")
- private final KeyPair seller;
- @SerializedName("selling")
- private final Asset selling;
- @SerializedName("buying")
- private final Asset buying;
- @SerializedName("amount")
- private final String amount;
- @SerializedName("price")
- private final String price;
- @SerializedName("_links")
- private final Links links;
-
- OfferResponse(Long id, String pagingToken, KeyPair seller, Asset selling, Asset buying, String amount, String price, Links links) {
- this.id = id;
- this.pagingToken = pagingToken;
- this.seller = seller;
- this.selling = selling;
- this.buying = buying;
- this.amount = amount;
- this.price = price;
- this.links = links;
- }
-
- public Long getId() {
- return id;
- }
-
- public String getPagingToken() {
- return pagingToken;
- }
-
- public KeyPair getSeller() {
- return seller;
- }
-
- public Asset getSelling() {
- return selling;
- }
-
- public Asset getBuying() {
- return buying;
- }
-
- public String getAmount() {
- return amount;
- }
-
- public String getPrice() {
- return price;
- }
-
- public Links getLinks() {
- return links;
- }
-
- /**
- * Links connected to ledger.
- */
- public static class Links {
- @SerializedName("self")
- private final Link self;
- @SerializedName("offer_maker")
- private final Link offerMager;
-
- public Links(Link self, Link offerMager) {
- this.self = self;
- this.offerMager = offerMager;
+ @SerializedName("id")
+ private final Long id;
+ @SerializedName("paging_token")
+ private final String pagingToken;
+ @SerializedName("seller")
+ private final KeyPair seller;
+ @SerializedName("selling")
+ private final Asset selling;
+ @SerializedName("buying")
+ private final Asset buying;
+ @SerializedName("amount")
+ private final String amount;
+ @SerializedName("price")
+ private final String price;
+ @SerializedName("_links")
+ private final Links links;
+
+ OfferResponse(Long id, String pagingToken, KeyPair seller, Asset selling, Asset buying, String amount, String price, Links links) {
+ this.id = id;
+ this.pagingToken = pagingToken;
+ this.seller = seller;
+ this.selling = selling;
+ this.buying = buying;
+ this.amount = amount;
+ this.price = price;
+ this.links = links;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getPagingToken() {
+ return pagingToken;
+ }
+
+ public KeyPair getSeller() {
+ return seller;
+ }
+
+ public Asset getSelling() {
+ return selling;
}
- public Link getSelf() {
- return self;
+ public Asset getBuying() {
+ return buying;
}
- public Link getOfferMager() {
- return offerMager;
+ public String getAmount() {
+ return amount;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ public Links getLinks() {
+ return links;
+ }
+
+ /**
+ * Links connected to ledger.
+ */
+ public static class Links {
+ @SerializedName("self")
+ private final Link self;
+ @SerializedName("offer_maker")
+ private final Link offerMager;
+
+ public Links(Link self, Link offerMager) {
+ this.self = self;
+ this.offerMager = offerMager;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
+
+ public Link getOfferMager() {
+ return offerMager;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/OperationDeserializer.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/OperationDeserializer.java
index 239d62a7..38bfd4b4 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/OperationDeserializer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/OperationDeserializer.java
@@ -6,7 +6,9 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
+
import java.lang.reflect.Type;
+
import kin.base.KeyPair;
import kin.base.responses.operations.AccountMergeOperationResponse;
import kin.base.responses.operations.AllowTrustOperationResponse;
@@ -22,39 +24,39 @@
import kin.base.responses.operations.SetOptionsOperationResponse;
class OperationDeserializer implements JsonDeserializer {
- @Override
- public OperationResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- // Create new Gson object with adapters needed in Operation
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
- .create();
+ @Override
+ public OperationResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ // Create new Gson object with adapters needed in Operation
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
+ .create();
- int type = json.getAsJsonObject().get("type_i").getAsInt();
- switch (type) {
- case 0:
- return gson.fromJson(json, CreateAccountOperationResponse.class);
- case 1:
- return gson.fromJson(json, PaymentOperationResponse.class);
- case 2:
- return gson.fromJson(json, PathPaymentOperationResponse.class);
- case 3:
- return gson.fromJson(json, ManageOfferOperationResponse.class);
- case 4:
- return gson.fromJson(json, CreatePassiveOfferOperationResponse.class);
- case 5:
- return gson.fromJson(json, SetOptionsOperationResponse.class);
- case 6:
- return gson.fromJson(json, ChangeTrustOperationResponse.class);
- case 7:
- return gson.fromJson(json, AllowTrustOperationResponse.class);
- case 8:
- return gson.fromJson(json, AccountMergeOperationResponse.class);
- case 9:
- return gson.fromJson(json, InflationOperationResponse.class);
- case 10:
- return gson.fromJson(json, ManageDataOperationResponse.class);
- default:
- throw new RuntimeException("Invalid operation type");
+ int type = json.getAsJsonObject().get("type_i").getAsInt();
+ switch (type) {
+ case 0:
+ return gson.fromJson(json, CreateAccountOperationResponse.class);
+ case 1:
+ return gson.fromJson(json, PaymentOperationResponse.class);
+ case 2:
+ return gson.fromJson(json, PathPaymentOperationResponse.class);
+ case 3:
+ return gson.fromJson(json, ManageOfferOperationResponse.class);
+ case 4:
+ return gson.fromJson(json, CreatePassiveOfferOperationResponse.class);
+ case 5:
+ return gson.fromJson(json, SetOptionsOperationResponse.class);
+ case 6:
+ return gson.fromJson(json, ChangeTrustOperationResponse.class);
+ case 7:
+ return gson.fromJson(json, AllowTrustOperationResponse.class);
+ case 8:
+ return gson.fromJson(json, AccountMergeOperationResponse.class);
+ case 9:
+ return gson.fromJson(json, InflationOperationResponse.class);
+ case 10:
+ return gson.fromJson(json, ManageDataOperationResponse.class);
+ default:
+ throw new RuntimeException("Invalid operation type");
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/OrderBookResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/OrderBookResponse.java
index 7a53b234..58723137 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/OrderBookResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/OrderBookResponse.java
@@ -1,15 +1,17 @@
package kin.base.responses;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.annotations.SerializedName;
+
import kin.base.Asset;
import kin.base.Price;
import kin.base.Server;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents order book response.
+ *
* @see Order book documentation
* @see kin.base.requests.OrderBookRequestBuilder
* @see Server#orderBook()
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/Page.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/Page.java
index 81a940dc..f2992dd2 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/Page.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/Page.java
@@ -2,76 +2,81 @@
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
+
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
+
import kin.base.requests.ResponseHandler;
import okhttp3.OkHttpClient;
/**
* Represents page of objects.
+ *
* @see Page documentation
*/
public class Page extends Response {
- @SerializedName("records")
- private ArrayList records;
- @SerializedName("links")
- private Links links;
+ @SerializedName("records")
+ private ArrayList records;
+ @SerializedName("links")
+ private Links links;
- Page() {}
+ Page() {
+ }
- public ArrayList getRecords() {
- return records;
- }
+ public ArrayList getRecords() {
+ return records;
+ }
- public Links getLinks() {
- return links;
- }
+ public Links getLinks() {
+ return links;
+ }
- /**
- * @return The next page of results or null when there is no more results
- * @throws URISyntaxException
- * @throws IOException
- * @param httpClient
- */
- public Page getNextPage(OkHttpClient httpClient) throws URISyntaxException, IOException {
- if (this.getLinks().getNext() == null) {
- return null;
+ /**
+ * @param httpClient
+ * @return The next page of results or null when there is no more results
+ * @throws URISyntaxException
+ * @throws IOException
+ */
+ public Page getNextPage(OkHttpClient httpClient) throws URISyntaxException, IOException {
+ if (this.getLinks().getNext() == null) {
+ return null;
+ }
+ TypeToken type = new TypeToken>() {
+ };
+ ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
+ URI uri = new URI(this.getLinks().getNext().getHref());
+ return responseHandler.handleGetRequest(uri);
}
- TypeToken type = new TypeToken>() {};
- ResponseHandler> responseHandler = new ResponseHandler>(httpClient, type);
- URI uri = new URI(this.getLinks().getNext().getHref());
- return responseHandler.handleGetRequest(uri);
- }
- /**
- * Links connected to page response.
- */
- public static class Links {
- @SerializedName("next")
- private final Link next;
- @SerializedName("prev")
- private final Link prev;
- @SerializedName("self")
- private final Link self;
+ /**
+ * Links connected to page response.
+ */
+ public static class Links {
+ @SerializedName("next")
+ private final Link next;
+ @SerializedName("prev")
+ private final Link prev;
+ @SerializedName("self")
+ private final Link self;
- Links(Link next, Link prev, Link self) {
- this.next = next;
- this.prev = prev;
- this.self = self;
- }
+ Links(Link next, Link prev, Link self) {
+ this.next = next;
+ this.prev = prev;
+ this.self = self;
+ }
- public Link getNext() {
- return next;
- }
+ public Link getNext() {
+ return next;
+ }
- public Link getPrev() {
- return prev;
- }
+ public Link getPrev() {
+ return prev;
+ }
- public Link getSelf() {
- return self;
+ public Link getSelf() {
+ return self;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/PageDeserializer.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/PageDeserializer.java
index d0f6d79a..ed1747d9 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/PageDeserializer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/PageDeserializer.java
@@ -8,42 +8,45 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
+
import java.lang.reflect.Type;
+
import kin.base.Asset;
import kin.base.KeyPair;
import kin.base.responses.effects.EffectResponse;
import kin.base.responses.operations.OperationResponse;
class PageDeserializer implements JsonDeserializer> {
- private TypeToken> pageType;
-
- /**
- * "Generics on a type are typically erased at runtime, except when the type is compiled with the
- * generic parameter bound. In that case, the compiler inserts the generic type information into
- * the compiled class. In other cases, that is not possible."
- * More info: http://stackoverflow.com/a/14506181
- * @param pageType
- */
- public PageDeserializer(TypeToken> pageType) {
- this.pageType = pageType;
- }
-
- @Override
- public Page deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- // Flatten the object so it has two fields `records` and `links`
- JsonObject newJson = new JsonObject();
- newJson.add("records", json.getAsJsonObject().get("_embedded").getAsJsonObject().get("records"));
- newJson.add("links", json.getAsJsonObject().get("_links"));
-
- // Create new Gson object with adapters needed in Page
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(Asset.class, new AssetDeserializer())
- .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
- .registerTypeAdapter(OperationResponse.class, new OperationDeserializer())
- .registerTypeAdapter(EffectResponse.class, new EffectDeserializer())
- .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer())
- .create();
-
- return gson.fromJson(newJson, pageType.getType());
- }
+ private TypeToken> pageType;
+
+ /**
+ * "Generics on a type are typically erased at runtime, except when the type is compiled with the
+ * generic parameter bound. In that case, the compiler inserts the generic type information into
+ * the compiled class. In other cases, that is not possible."
+ * More info: http://stackoverflow.com/a/14506181
+ *
+ * @param pageType
+ */
+ public PageDeserializer(TypeToken> pageType) {
+ this.pageType = pageType;
+ }
+
+ @Override
+ public Page deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ // Flatten the object so it has two fields `records` and `links`
+ JsonObject newJson = new JsonObject();
+ newJson.add("records", json.getAsJsonObject().get("_embedded").getAsJsonObject().get("records"));
+ newJson.add("links", json.getAsJsonObject().get("_links"));
+
+ // Create new Gson object with adapters needed in Page
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(Asset.class, new AssetDeserializer())
+ .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
+ .registerTypeAdapter(OperationResponse.class, new OperationDeserializer())
+ .registerTypeAdapter(EffectResponse.class, new EffectDeserializer())
+ .registerTypeAdapter(TransactionResponse.class, new TransactionDeserializer())
+ .create();
+
+ return gson.fromJson(newJson, pageType.getType());
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/PathResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/PathResponse.java
index d5832a19..92f58da9 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/PathResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/PathResponse.java
@@ -1,7 +1,9 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import java.util.ArrayList;
+
import kin.base.Asset;
import kin.base.AssetTypeNative;
import kin.base.KeyPair;
@@ -9,95 +11,96 @@
/**
* Represents path response.
+ *
* @see Path documentation
* @see kin.base.requests.PathsRequestBuilder
* @see Server#paths()
*/
public class PathResponse extends Response {
- @SerializedName("destination_amount")
- private final String destinationAmount;
- @SerializedName("destination_asset_type")
- private final String destinationAssetType;
- @SerializedName("destination_asset_code")
- private final String destinationAssetCode;
- @SerializedName("destination_asset_issuer")
- private final String destinationAssetIssuer;
-
- @SerializedName("source_amount")
- private final String sourceAmount;
- @SerializedName("source_asset_type")
- private final String sourceAssetType;
- @SerializedName("source_asset_code")
- private final String sourceAssetCode;
- @SerializedName("source_asset_issuer")
- private final String sourceAssetIssuer;
-
- @SerializedName("path")
- private final ArrayList path;
-
- @SerializedName("_links")
- private final Links links;
-
- PathResponse(String destinationAmount, String destinationAssetType, String destinationAssetCode, String destinationAssetIssuer, String sourceAmount, String sourceAssetType, String sourceAssetCode, String sourceAssetIssuer, ArrayList path, Links links) {
- this.destinationAmount = destinationAmount;
- this.destinationAssetType = destinationAssetType;
- this.destinationAssetCode = destinationAssetCode;
- this.destinationAssetIssuer = destinationAssetIssuer;
- this.sourceAmount = sourceAmount;
- this.sourceAssetType = sourceAssetType;
- this.sourceAssetCode = sourceAssetCode;
- this.sourceAssetIssuer = sourceAssetIssuer;
- this.path = path;
- this.links = links;
- }
-
- public String getDestinationAmount() {
- return destinationAmount;
- }
-
- public String getSourceAmount() {
- return sourceAmount;
- }
-
- public ArrayList getPath() {
- return path;
- }
-
- public Asset getDestinationAsset() {
- if (destinationAssetType.equals("native")) {
- return new AssetTypeNative();
- } else {
- KeyPair issuer = KeyPair.fromAccountId(destinationAssetIssuer);
- return Asset.createNonNativeAsset(destinationAssetCode, issuer);
+ @SerializedName("destination_amount")
+ private final String destinationAmount;
+ @SerializedName("destination_asset_type")
+ private final String destinationAssetType;
+ @SerializedName("destination_asset_code")
+ private final String destinationAssetCode;
+ @SerializedName("destination_asset_issuer")
+ private final String destinationAssetIssuer;
+
+ @SerializedName("source_amount")
+ private final String sourceAmount;
+ @SerializedName("source_asset_type")
+ private final String sourceAssetType;
+ @SerializedName("source_asset_code")
+ private final String sourceAssetCode;
+ @SerializedName("source_asset_issuer")
+ private final String sourceAssetIssuer;
+
+ @SerializedName("path")
+ private final ArrayList path;
+
+ @SerializedName("_links")
+ private final Links links;
+
+ PathResponse(String destinationAmount, String destinationAssetType, String destinationAssetCode, String destinationAssetIssuer, String sourceAmount, String sourceAssetType, String sourceAssetCode, String sourceAssetIssuer, ArrayList path, Links links) {
+ this.destinationAmount = destinationAmount;
+ this.destinationAssetType = destinationAssetType;
+ this.destinationAssetCode = destinationAssetCode;
+ this.destinationAssetIssuer = destinationAssetIssuer;
+ this.sourceAmount = sourceAmount;
+ this.sourceAssetType = sourceAssetType;
+ this.sourceAssetCode = sourceAssetCode;
+ this.sourceAssetIssuer = sourceAssetIssuer;
+ this.path = path;
+ this.links = links;
}
- }
-
- public Asset getSourceAsset() {
- if (sourceAssetType.equals("native")) {
- return new AssetTypeNative();
- } else {
- KeyPair issuer = KeyPair.fromAccountId(sourceAssetIssuer);
- return Asset.createNonNativeAsset(sourceAssetCode, issuer);
+
+ public String getDestinationAmount() {
+ return destinationAmount;
}
- }
- public Links getLinks() {
- return links;
- }
+ public String getSourceAmount() {
+ return sourceAmount;
+ }
- /**
- * Links connected to path.
- */
- public static class Links {
- @SerializedName("self")
- private final Link self;
+ public ArrayList getPath() {
+ return path;
+ }
+
+ public Asset getDestinationAsset() {
+ if (destinationAssetType.equals("native")) {
+ return new AssetTypeNative();
+ } else {
+ KeyPair issuer = KeyPair.fromAccountId(destinationAssetIssuer);
+ return Asset.createNonNativeAsset(destinationAssetCode, issuer);
+ }
+ }
- Links(Link self) {
- this.self = self;
+ public Asset getSourceAsset() {
+ if (sourceAssetType.equals("native")) {
+ return new AssetTypeNative();
+ } else {
+ KeyPair issuer = KeyPair.fromAccountId(sourceAssetIssuer);
+ return Asset.createNonNativeAsset(sourceAssetCode, issuer);
+ }
}
- public Link getSelf() {
- return self;
+ public Links getLinks() {
+ return links;
+ }
+
+ /**
+ * Links connected to path.
+ */
+ public static class Links {
+ @SerializedName("self")
+ private final Link self;
+
+ Links(Link self) {
+ this.self = self;
+ }
+
+ public Link getSelf() {
+ return self;
+ }
}
- }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/Response.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/Response.java
index df837bc3..596c71b6 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/Response.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/Response.java
@@ -1,48 +1,51 @@
package kin.base.responses;
public abstract class Response {
- protected int rateLimitLimit;
- protected int rateLimitRemaining;
- protected int rateLimitReset;
+ protected int rateLimitLimit;
+ protected int rateLimitRemaining;
+ protected int rateLimitReset;
- public void setHeaders(String limit, String remaining, String reset) {
- try {
- this.rateLimitLimit = Integer.parseInt(limit);
- this.rateLimitRemaining = Integer.parseInt(remaining);
- this.rateLimitReset = Integer.parseInt(reset);
- } catch (Exception e) {
- e.printStackTrace();
+ public void setHeaders(String limit, String remaining, String reset) {
+ try {
+ this.rateLimitLimit = safeParse(limit);
+ this.rateLimitRemaining = safeParse(remaining);
+ this.rateLimitReset = safeParse(reset);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- }
- private int safeParse(String number) {
- return number == null || number.isEmpty() ? 0 : Integer.parseInt(number);
- }
+ private int safeParse(String number) {
+ return number == null || number.isEmpty() ? 0 : Integer.parseInt(number);
+ }
- /**
- * Returns X-RateLimit-Limit header from the response.
- * This number represents the he maximum number of requests that the current client can
- * make in one hour.
- * @see Rate Limiting
- */
- public int getRateLimitLimit() {
- return rateLimitLimit;
- }
+ /**
+ * Returns X-RateLimit-Limit header from the response.
+ * This number represents the he maximum number of requests that the current client can
+ * make in one hour.
+ *
+ * @see Rate Limiting
+ */
+ public int getRateLimitLimit() {
+ return rateLimitLimit;
+ }
- /**
- * Returns X-RateLimit-Remaining header from the response.
- * The number of remaining requests for the current window.
- * @see Rate Limiting
- */
- public int getRateLimitRemaining() {
- return rateLimitRemaining;
- }
+ /**
+ * Returns X-RateLimit-Remaining header from the response.
+ * The number of remaining requests for the current window.
+ *
+ * @see Rate Limiting
+ */
+ public int getRateLimitRemaining() {
+ return rateLimitRemaining;
+ }
- /**
- * Returns X-RateLimit-Reset header from the response. Seconds until a new window starts.
- * @see Rate Limiting
- */
- public int getRateLimitReset() {
- return rateLimitReset;
- }
+ /**
+ * Returns X-RateLimit-Reset header from the response. Seconds until a new window starts.
+ *
+ * @see Rate Limiting
+ */
+ public int getRateLimitReset() {
+ return rateLimitReset;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/SubmitTransactionResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/SubmitTransactionResponse.java
index 6bbc3a62..ba5bde46 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/SubmitTransactionResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/SubmitTransactionResponse.java
@@ -1,9 +1,11 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
+
import kin.base.Server;
import kin.base.Transaction;
import kin.base.codec.Base64;
@@ -13,6 +15,7 @@
/**
* Represents server response after submitting transaction.
+ *
* @see Server#submitTransaction(Transaction)
*/
public class SubmitTransactionResponse extends Response {
@@ -66,6 +69,7 @@ public String getResultXdr() {
/**
* Helper method that returns Offer ID for ManageOffer from TransactionResult Xdr.
* This is helpful when you need ID of an offer to update it later.
+ *
* @param position Position of ManageOffer operation. If ManageOffer is second operation in this transaction this should be equal 1.
* @return Offer ID or null when operation at position is not a ManageOffer operation or error has occurred.
*/
@@ -150,6 +154,7 @@ public ResultCodes getResultCodes() {
/**
* Contains result codes for this transaction.
+ *
* @see Possible values
*/
public static class ResultCodes {
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/TradeResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/TradeResponse.java
index a052d40a..06270f39 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/TradeResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/TradeResponse.java
@@ -1,11 +1,13 @@
package kin.base.responses;
import com.google.gson.annotations.SerializedName;
+
import kin.base.KeyPair;
import kin.base.Server;
/**
* Represents trades response.
+ *
* @see Trades for Orderbook documentation
* @see kin.base.requests.TradesRequestBuilder
* @see Server#trades()
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionDeserializer.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionDeserializer.java
index bff03df6..8696b424 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionDeserializer.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionDeserializer.java
@@ -6,52 +6,54 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
+
import java.lang.reflect.Type;
+
import kin.base.KeyPair;
import kin.base.Memo;
import kin.base.codec.Base64;
public class TransactionDeserializer implements JsonDeserializer {
- @Override
- public TransactionResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- // Create new Gson object with adapters needed in Transaction
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
- .create();
+ @Override
+ public TransactionResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ // Create new Gson object with adapters needed in Transaction
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(KeyPair.class, new KeyPairTypeAdapter().nullSafe())
+ .create();
- TransactionResponse transaction = gson.fromJson(json, TransactionResponse.class);
+ TransactionResponse transaction = gson.fromJson(json, TransactionResponse.class);
- String memoType = json.getAsJsonObject().get("memo_type").getAsString();
- Memo memo;
- if (memoType.equals("none")) {
- memo = Memo.none();
- } else {
- // Because of the way "encoding/json" works on structs in Go, if transaction
- // has an empty `memo_text` value, the `memo` field won't be present in a JSON
- // representation of a transaction. That's why we need to handle a special case
- // here.
- if (memoType.equals("text")) {
- JsonElement memoField = json.getAsJsonObject().get("memo");
- if (memoField != null) {
- memo = Memo.text(memoField.getAsString());
- } else {
- memo = Memo.text("");
- }
- } else {
- String memoValue = json.getAsJsonObject().get("memo").getAsString();
- if (memoType.equals("id")) {
- memo = Memo.id(Long.parseLong(memoValue));
- } else if (memoType.equals("hash")) {
- memo = Memo.hash(Base64.decodeBase64(memoValue));
- } else if (memoType.equals("return")) {
- memo = Memo.returnHash(Base64.decodeBase64(memoValue));
+ String memoType = json.getAsJsonObject().get("memo_type").getAsString();
+ Memo memo;
+ if (memoType.equals("none")) {
+ memo = Memo.none();
} else {
- throw new JsonParseException("Unknown memo type.");
+ // Because of the way "encoding/json" works on structs in Go, if transaction
+ // has an empty `memo_text` value, the `memo` field won't be present in a JSON
+ // representation of a transaction. That's why we need to handle a special case
+ // here.
+ if (memoType.equals("text")) {
+ JsonElement memoField = json.getAsJsonObject().get("memo");
+ if (memoField != null) {
+ memo = Memo.text(memoField.getAsString());
+ } else {
+ memo = Memo.text("");
+ }
+ } else {
+ String memoValue = json.getAsJsonObject().get("memo").getAsString();
+ if (memoType.equals("id")) {
+ memo = Memo.id(Long.parseLong(memoValue));
+ } else if (memoType.equals("hash")) {
+ memo = Memo.hash(Base64.decodeBase64(memoValue));
+ } else if (memoType.equals("return")) {
+ memo = Memo.returnHash(Base64.decodeBase64(memoValue));
+ } else {
+ throw new JsonParseException("Unknown memo type.");
+ }
+ }
}
- }
- }
- transaction.setMemo(memo);
- return transaction;
- }
+ transaction.setMemo(memo);
+ return transaction;
+ }
}
diff --git a/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionResponse.java b/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionResponse.java
index fac2af39..8d06ce3e 100644
--- a/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionResponse.java
+++ b/kin-sdk/kin-base/src/main/java/kin/base/responses/TransactionResponse.java
@@ -1,12 +1,12 @@
package kin.base.responses;
-import static kin.base.Util.checkNotNull;
-
import com.google.gson.annotations.SerializedName;
+
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
+
import kin.base.KeyPair;
import kin.base.LedgerEntryChanges;
import kin.base.Memo;
@@ -18,6 +18,8 @@
import kin.base.xdr.TransactionMeta;
import kin.base.xdr.XdrDataInputStream;
+import static kin.base.Util.checkNotNull;
+
/**
* Represents transaction response.
*
@@ -26,212 +28,212 @@
* @see Server#transactions()
*/
public class TransactionResponse extends Response {
- @SerializedName("hash")
- private final String hash;
- @SerializedName("ledger")
- private final Long ledger;
- @SerializedName("created_at")
- private final String createdAt;
- @SerializedName("source_account")
- private final KeyPair sourceAccount;
- @SerializedName("paging_token")
- private final String pagingToken;
- @SerializedName("source_account_sequence")
- private final Long sourceAccountSequence;
- @SerializedName("fee_paid")
- private final Long feePaid;
- @SerializedName("operation_count")
- private final Integer operationCount;
- @SerializedName("envelope_xdr")
- private final String envelopeXdr;
- @SerializedName("result_xdr")
- private final String resultXdr;
- @SerializedName("result_meta_xdr")
- private final String resultMetaXdr;
- @SerializedName("_links")
- private final Links links;
-
- // GSON won't serialize `transient` variables automatically. We need this behaviour
- // because Memo is an abstract class and GSON tries to instantiate it.
- private transient Memo memo;
-
- TransactionResponse(String hash, Long ledger, String createdAt, KeyPair sourceAccount, String pagingToken, Long sourceAccountSequence, Long feePaid, Integer operationCount, String envelopeXdr, String resultXdr, String resultMetaXdr, Memo memo, Links links) {
- this.hash = hash;
- this.ledger = ledger;
- this.createdAt = createdAt;
- this.sourceAccount = sourceAccount;
- this.pagingToken = pagingToken;
- this.sourceAccountSequence = sourceAccountSequence;
- this.feePaid = feePaid;
- this.operationCount = operationCount;
- this.envelopeXdr = envelopeXdr;
- this.resultXdr = resultXdr;
- this.resultMetaXdr = resultMetaXdr;
- this.memo = memo;
- this.links = links;
- }
-
- public String getHash() {
- return hash;
- }
-
- public Long getLedger() {
- return ledger;
- }
-
- public String getCreatedAt() {
- return createdAt;
- }
-
- public KeyPair getSourceAccount() {
- return sourceAccount;
- }
-
- public String getPagingToken() {
- return pagingToken;
- }
-
- public Long getSourceAccountSequence() {
- return sourceAccountSequence;
- }
-
- public Long getFeePaid() {
- return feePaid;
- }
-
- public Integer getOperationCount() {
- return operationCount;
- }
-
- public String getEnvelopeXdr() {
- return envelopeXdr;
- }
-
- public String getResultXdr() {
- return resultXdr;
- }
-
- public String getResultMetaXdr() {
- return resultMetaXdr;
- }
-
- public Memo getMemo() {
- return memo;
- }
-
- public List getOperations() {
- String envelopeXdr = getEnvelopeXdr();
- try {
- Transaction transaction = extractTransaction(envelopeXdr);
- kin.base.xdr.Operation[] xdrOperations = transaction.getOperations();
- ArrayList operationsList = new ArrayList<>(xdrOperations.length);
- for (kin.base.xdr.Operation xdrOperation : xdrOperations) {
- operationsList.add(Operation.fromXdr(xdrOperation));
- }
- return operationsList;
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private Transaction extractTransaction(String envelopeXdr) throws IOException {
- XdrDataInputStream xdrDataInputStream = Util.createXdrDataInputStream(envelopeXdr);
- return Transaction.decode(xdrDataInputStream);
- }
-
- public List getLedgerChanges() {
- String resultMetaXdr = getResultMetaXdr();
- try {
- TransactionMeta transactionMeta = extractTransactionMeta(resultMetaXdr);
- OperationMeta[] operationMetas = transactionMeta.getOperations();
- ArrayList ledgerChangesList = new ArrayList<>(operationMetas.length);
- for (OperationMeta operationMeta : operationMetas) {
- ledgerChangesList.add(LedgerEntryChanges.fromXdr(operationMeta.getChanges()));
- }
- return ledgerChangesList;
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private TransactionMeta extractTransactionMeta(String envelopeXdr) throws IOException {
- XdrDataInputStream xdrDataInputStream = Util.createXdrDataInputStream(envelopeXdr);
- return TransactionMeta.decode(xdrDataInputStream);
- }
-
- public void setMemo(Memo memo) {
- memo = checkNotNull(memo, "memo cannot be null");
- if (this.memo != null) {
- throw new RuntimeException("Memo has been already set.");
- }
- this.memo = memo;
- }
-
- public Links getLinks() {
- return links;
- }
-
- /**
- * Links connected to transaction.
- */
- public static class Links {
- @SerializedName("account")
- private final Link account;
- @SerializedName("effects")
- private final Link effects;
+ @SerializedName("hash")
+ private final String hash;
@SerializedName("ledger")
- private final Link ledger;
- @SerializedName("operations")
- private final Link operations;
- @SerializedName("precedes")
- private final Link precedes;
- @SerializedName("self")
- private final Link self;
- @SerializedName("succeeds")
- private final Link succeeds;
+ private final Long ledger;
+ @SerializedName("created_at")
+ private final String createdAt;
+ @SerializedName("source_account")
+ private final KeyPair sourceAccount;
+ @SerializedName("paging_token")
+ private final String pagingToken;
+ @SerializedName("source_account_sequence")
+ private final Long sourceAccountSequence;
+ @SerializedName("fee_paid")
+ private final Long feePaid;
+ @SerializedName("operation_count")
+ private final Integer operationCount;
+ @SerializedName("envelope_xdr")
+ private final String envelopeXdr;
+ @SerializedName("result_xdr")
+ private final String resultXdr;
+ @SerializedName("result_meta_xdr")
+ private final String resultMetaXdr;
+ @SerializedName("_links")
+ private final Links links;
+
+ // GSON won't serialize `transient` variables automatically. We need this behaviour
+ // because Memo is an abstract class and GSON tries to instantiate it.
+ private transient Memo memo;
+
+ TransactionResponse(String hash, Long ledger, String createdAt, KeyPair sourceAccount, String pagingToken, Long sourceAccountSequence, Long feePaid, Integer operationCount, String envelopeXdr, String resultXdr, String resultMetaXdr, Memo memo, Links links) {
+ this.hash = hash;
+ this.ledger = ledger;
+ this.createdAt = createdAt;
+ this.sourceAccount = sourceAccount;
+ this.pagingToken = pagingToken;
+ this.sourceAccountSequence = sourceAccountSequence;
+ this.feePaid = feePaid;
+ this.operationCount = operationCount;
+ this.envelopeXdr = envelopeXdr;
+ this.resultXdr = resultXdr;
+ this.resultMetaXdr = resultMetaXdr;
+ this.memo = memo;
+ this.links = links;
+ }
+
+ public String getHash() {
+ return hash;
+ }
+
+ public Long getLedger() {
+ return ledger;
+ }
+
+ public String getCreatedAt() {
+ return createdAt;
+ }
+
+ public KeyPair getSourceAccount() {
+ return sourceAccount;
+ }
+
+ public String getPagingToken() {
+ return pagingToken;
+ }
+
+ public Long getSourceAccountSequence() {
+ return sourceAccountSequence;
+ }
+
+ public Long getFeePaid() {
+ return feePaid;
+ }
+
+ public Integer getOperationCount() {
+ return operationCount;
+ }
+
+ public String getEnvelopeXdr() {
+ return envelopeXdr;
+ }
+
+ public String getResultXdr() {
+ return resultXdr;
+ }
+
+ public String getResultMetaXdr() {
+ return resultMetaXdr;
+ }
- Links(Link account, Link effects, Link ledger, Link operations, Link self, Link precedes, Link succeeds) {
- this.account = account;
- this.effects = effects;
- this.ledger = ledger;
- this.operations = operations;
- this.self = self;
- this.precedes = precedes;
- this.succeeds = succeeds;
+ public Memo getMemo() {
+ return memo;
}
- public Link getAccount() {
- return account;
+ public List getOperations() {
+ String envelopeXdr = getEnvelopeXdr();
+ try {
+ Transaction transaction = extractTransaction(envelopeXdr);
+ kin.base.xdr.Operation[] xdrOperations = transaction.getOperations();
+ ArrayList operationsList = new ArrayList