From e618573914e84e951369d37e1fb171fbc13d391a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adriano=20Lu=C3=ADs=20Rocha?= Date: Sun, 14 Oct 2018 02:25:23 -0400 Subject: [PATCH] Add support to TLS v1.2 through BounceCastle Change way to perform and enable SSL Pinning Add .editorconfig file Add .gitattributes to ensure file format Format code with new editor config settings --- .editorconfig | 28 + .gitattributes | 16 + .travis.yml | 1 - LICENSE | 2 +- README.md | 14 +- pom.xml | 11 +- src/main/java/me/pagar/Address.java | 242 +-- src/main/java/me/pagar/AntifraudAnalysis.java | 88 +- src/main/java/me/pagar/Balance.java | 90 +- src/main/java/me/pagar/BankAccount.java | 276 +-- src/main/java/me/pagar/BulkAnticipation.java | 254 +-- src/main/java/me/pagar/Card.java | 464 ++--- src/main/java/me/pagar/CardHashKey.java | 48 +- src/main/java/me/pagar/Customer.java | 306 +-- src/main/java/me/pagar/PagarMe.java | 119 +- src/main/java/me/pagar/PagarMeError.java | 40 +- src/main/java/me/pagar/PagarMeException.java | 120 +- src/main/java/me/pagar/PagarMeModel.java | 420 ++-- src/main/java/me/pagar/PagarMeRequest.java | 68 +- src/main/java/me/pagar/PagarMeResponse.java | 38 +- src/main/java/me/pagar/Payable.java | 126 +- src/main/java/me/pagar/Phone.java | 120 +- src/main/java/me/pagar/Postback.java | 214 +- src/main/java/me/pagar/Recipient.java | 470 ++--- src/main/java/me/pagar/RestClient.java | 341 ++-- src/main/java/me/pagar/SplitRule.java | 108 +- src/main/java/me/pagar/Transaction.java | 1730 ++++++++--------- src/main/java/me/pagar/Transfer.java | 206 +- .../pagar/util/BulkAnticipationAdapter.java | 32 +- .../java/me/pagar/util/DateTimeAdapter.java | 40 +- src/main/java/me/pagar/util/JsonUtils.java | 70 +- .../java/me/pagar/util/LocalDateAdapter.java | 40 +- src/main/java/me/pagar/util/MapUtils.java | 120 +- .../pagar/util/PagarMeSSLSocketFactory.java | 337 ++++ src/test/java/me/pagar/BalanceTest.java | 22 +- src/test/java/me/pagar/BankAccountTest.java | 50 +- src/test/java/me/pagar/BaseTest.java | 14 +- src/test/java/me/pagar/CardTest.java | 78 +- src/test/java/me/pagar/CustomerTest.java | 96 +- src/test/java/me/pagar/PagarMeTest.java | 20 +- src/test/java/me/pagar/RecipientTest.java | 134 +- src/test/java/me/pagar/TransactionTest.java | 86 +- src/test/java/me/pagar/util/MapUtilsTest.java | 112 +- src/test/resources/log4j.properties | 4 +- 44 files changed, 3791 insertions(+), 3424 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 src/main/java/me/pagar/util/PagarMeSSLSocketFactory.java diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b2e24b6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,28 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.xml] +indent_style = tab +indent_size = 4 + +[*.java] +indent_style = tab +indent_size = 4 +continuation_indent_size = 8 + +[*.bat] +indent_style = tab +end_of_line = crlf + +[*.md] +trim_trailing_whitespace = false + +[LICENSE] +insert_final_newline = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..2ddbb7d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,16 @@ +# Set default behaviour, in case users don't have core.autocrlf set. +* text=auto + +# Explicitly declare text files we want to always be normalized and converted +# to native line endings on checkout. +*.java text +*.xml text + +# Declare files that will always have LF line endings on checkout. +*.sh eol=lf + +# Declare files that will always have CRLF line endings on checkout. +*.bat text eol=crlf + +# Denote all files that are truly binary and should not be modified. +*.crt binary diff --git a/.travis.yml b/.travis.yml index 6da39a0..53a391b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,5 @@ jdk: branches: only: - master - - develop script: mvn verify diff --git a/LICENSE b/LICENSE index fa9569c..1c7ebfd 100644 --- a/LICENSE +++ b/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 944ab10..807e2cc 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Basta colocar o seguinte trecho de código nas configurações de compilação a me.pagar pagarme-java - 1.4.0 + 1.4.1 ``` @@ -48,7 +48,7 @@ repositories { ##### Dependência ```groovy -compile('me.pagar:pagarme-java:1.4.0') { +compile('me.pagar:pagarme-java:1.4.1') { transitive = true } ``` @@ -57,14 +57,14 @@ compile('me.pagar:pagarme-java:1.4.0') { ##### Dependência ``` -'me.pagar:pagarme-java:jar:1.4.0' +'me.pagar:pagarme-java:jar:1.4.1' ``` #### Apache Ivy ##### Dependência ```xml - + ``` @@ -74,7 +74,7 @@ compile('me.pagar:pagarme-java:1.4.0') { ##### Dependência ```groovy @Grapes( - @Grab(group='me.pagar', module='pagarme-java', version='1.4.0') + @Grab(group='me.pagar', module='pagarme-java', version='1.4.1') ) ``` @@ -82,14 +82,14 @@ compile('me.pagar:pagarme-java:1.4.0') { ##### Dependência ```scala -libraryDependencies += "me.pagar" % "pagarme-java" % "1.4.0" +libraryDependencies += "me.pagar" % "pagarme-java" % "1.4.1" ``` #### Leiningen ##### Dependência ```clojure -[me.pagar/pagarme-java "1.4.0"] +[me.pagar/pagarme-java "1.4.1"] ``` ## Licença diff --git a/pom.xml b/pom.xml index 86c1056..a587993 100644 --- a/pom.xml +++ b/pom.xml @@ -6,14 +6,14 @@ me.pagar pagarme-java - 1.4.0 + 1.4.1 jar 2.7 2.8.2 - 3.0.2 + 2.6 2.19.1 0.12 @@ -26,6 +26,7 @@ 1.2 1.7.25 4.12 + 1.60 github @@ -94,6 +95,12 @@ ${version.slf4j} true + + org.bouncycastle + bcprov-jdk15on + ${version.bouncycastle} + true + junit junit diff --git a/src/main/java/me/pagar/Address.java b/src/main/java/me/pagar/Address.java index ef169cc..8e98d09 100644 --- a/src/main/java/me/pagar/Address.java +++ b/src/main/java/me/pagar/Address.java @@ -5,127 +5,127 @@ public class Address extends PagarMeModel { - @Expose - private String street; + @Expose + private String street; - @Expose - private String complementary; - - @Expose - private String streetNumber; - - @Expose - private String neighborhood; - - @Expose - private String city; - - @Expose - private String state; - - @Expose - private String zipcode; - - @Expose - private String country; - - public Address() { - super(); - } - - public Address(final String street, final String streetNumber, final String neighborhood, final String zipcode) { - this(); - this.street = street; - this.streetNumber = streetNumber; - this.neighborhood = neighborhood; - this.zipcode = zipcode; - } - - public String getStreet() { - return street; - } - - public String getComplementary() { - return complementary; - } - - public String getStreetNumber() { - return streetNumber; - } - - public String getNeighborhood() { - return neighborhood; - } - - public String getCity() { - return city; - } - - public String getState() { - return state; - } - - public String getZipcode() { - return zipcode; - } - - public String getCountry() { - return country; - } - - @Override - public DateTime getCreatedAt() { - throw new UnsupportedOperationException("Not allowed."); - } - - public void setStreet(final String street) { - this.street = street; - addUnsavedProperty("street"); - } - - public void setComplementary(final String complementary) { - this.complementary = complementary; - addUnsavedProperty("complementary"); - } - - public void setStreetNumber(final String streetNumber) { - this.streetNumber = streetNumber; - addUnsavedProperty("streetNumber"); - } - - public void setNeighborhood(final String neighborhood) { - this.neighborhood = neighborhood; - addUnsavedProperty("neighborhood"); - } - - public void setCity(final String city) { - this.city = city; - addUnsavedProperty("city"); - } - - public void setState(final String state) { - this.state = state; - addUnsavedProperty("state"); - } - - public void setZipcode(final String zipcode) { - this.zipcode = zipcode; - addUnsavedProperty("zipcode"); - } - - public void setCountry(final String country) { - this.country = country; - addUnsavedProperty("country"); - } - - @Override - public void setId(Integer id) { - throw new UnsupportedOperationException("Not allowed."); - } - - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Expose + private String complementary; + + @Expose + private String streetNumber; + + @Expose + private String neighborhood; + + @Expose + private String city; + + @Expose + private String state; + + @Expose + private String zipcode; + + @Expose + private String country; + + public Address() { + super(); + } + + public Address(final String street, final String streetNumber, final String neighborhood, final String zipcode) { + this(); + this.street = street; + this.streetNumber = streetNumber; + this.neighborhood = neighborhood; + this.zipcode = zipcode; + } + + public String getStreet() { + return street; + } + + public String getComplementary() { + return complementary; + } + + public String getStreetNumber() { + return streetNumber; + } + + public String getNeighborhood() { + return neighborhood; + } + + public String getCity() { + return city; + } + + public String getState() { + return state; + } + + public String getZipcode() { + return zipcode; + } + + public String getCountry() { + return country; + } + + @Override + public DateTime getCreatedAt() { + throw new UnsupportedOperationException("Not allowed."); + } + + public void setStreet(final String street) { + this.street = street; + addUnsavedProperty("street"); + } + + public void setComplementary(final String complementary) { + this.complementary = complementary; + addUnsavedProperty("complementary"); + } + + public void setStreetNumber(final String streetNumber) { + this.streetNumber = streetNumber; + addUnsavedProperty("streetNumber"); + } + + public void setNeighborhood(final String neighborhood) { + this.neighborhood = neighborhood; + addUnsavedProperty("neighborhood"); + } + + public void setCity(final String city) { + this.city = city; + addUnsavedProperty("city"); + } + + public void setState(final String state) { + this.state = state; + addUnsavedProperty("state"); + } + + public void setZipcode(final String zipcode) { + this.zipcode = zipcode; + addUnsavedProperty("zipcode"); + } + + public void setCountry(final String country) { + this.country = country; + addUnsavedProperty("country"); + } + + @Override + public void setId(Integer id) { + throw new UnsupportedOperationException("Not allowed."); + } + + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } } diff --git a/src/main/java/me/pagar/AntifraudAnalysis.java b/src/main/java/me/pagar/AntifraudAnalysis.java index d63c671..c8210ed 100644 --- a/src/main/java/me/pagar/AntifraudAnalysis.java +++ b/src/main/java/me/pagar/AntifraudAnalysis.java @@ -8,66 +8,66 @@ public class AntifraudAnalysis extends PagarMeModel { - @Expose(serialize = false) - private Integer cost; + @Expose(serialize = false) + private Integer cost; - @Expose(serialize = false) - private String name; + @Expose(serialize = false) + private String name; - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - @Expose(serialize = false) - private BigDecimal score; + @Expose(serialize = false) + private BigDecimal score; - @Expose(serialize = false) - private Status status; + @Expose(serialize = false) + private Status status; - public Integer getCost() { - return cost; - } + public Integer getCost() { + return cost; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public DateTime getUpdatedAt() { - return updatedAt; - } + public DateTime getUpdatedAt() { + return updatedAt; + } - public BigDecimal getScore() { - return score; - } + public BigDecimal getScore() { + return score; + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - @Override - public void setId(Integer id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(Integer id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } - public enum Status { + public enum Status { - @SerializedName("approved") - APPROVED, + @SerializedName("approved") + APPROVED, - @SerializedName("failed") - FAILED, + @SerializedName("failed") + FAILED, - @SerializedName("processing") - PROCESSING, + @SerializedName("processing") + PROCESSING, - @SerializedName("refused") - REFUSED + @SerializedName("refused") + REFUSED - } + } } diff --git a/src/main/java/me/pagar/Balance.java b/src/main/java/me/pagar/Balance.java index 3bef07b..58a3bca 100644 --- a/src/main/java/me/pagar/Balance.java +++ b/src/main/java/me/pagar/Balance.java @@ -9,64 +9,64 @@ public class Balance extends PagarMeModel { - @Expose(serialize = false) - private Summary waitingFunds; + @Expose(serialize = false) + private Summary waitingFunds; - @Expose(serialize = false) - private Summary available; + @Expose(serialize = false) + private Summary available; - @Expose(serialize = false) - private Summary transferred; + @Expose(serialize = false) + private Summary transferred; - public Balance() { - super.setClassName(getClass().getSimpleName().toLowerCase()); - } + public Balance() { + super.setClassName(getClass().getSimpleName().toLowerCase()); + } - public Summary getWaitingFunds() { - return waitingFunds; - } + public Summary getWaitingFunds() { + return waitingFunds; + } - public Summary getAvailable() { - return available; - } + public Summary getAvailable() { + return available; + } - public Summary getTransferred() { - return transferred; - } + public Summary getTransferred() { + return transferred; + } - @Override - public void setId(Serializable id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(Serializable id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } - public Balance refresh() throws PagarMeException { - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s", getClassName())); - final Balance other = JsonUtils.getAsObject((JsonObject) request.execute(), Balance.class); - copy(other); - flush(); - return other; - } + public Balance refresh() throws PagarMeException { + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s", getClassName())); + final Balance other = JsonUtils.getAsObject((JsonObject) request.execute(), Balance.class); + copy(other); + flush(); + return other; + } - private void copy(Balance other) { - this.waitingFunds = other.waitingFunds; - this.available = other.available; - this.transferred = other.transferred; - } + private void copy(Balance other) { + this.waitingFunds = other.waitingFunds; + this.available = other.available; + this.transferred = other.transferred; + } - public static class Summary { + public static class Summary { - @Expose(serialize = false) - private Integer amount; + @Expose(serialize = false) + private Integer amount; - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - } + } } diff --git a/src/main/java/me/pagar/BankAccount.java b/src/main/java/me/pagar/BankAccount.java index 317dcbb..bbc5d22 100644 --- a/src/main/java/me/pagar/BankAccount.java +++ b/src/main/java/me/pagar/BankAccount.java @@ -9,151 +9,151 @@ public class BankAccount extends PagarMeModel { - @Expose(serialize = false) - private Boolean chargeTransferFees; + @Expose(serialize = false) + private Boolean chargeTransferFees; - @Expose - private String bankCode; + @Expose + private String bankCode; - @Expose - private String agencia; + @Expose + private String agencia; - @Expose - private String agenciaDv; + @Expose + private String agenciaDv; - @Expose - private String conta; + @Expose + private String conta; - @Expose - private String contaDv; + @Expose + private String contaDv; - @Expose - private String documentNumber; + @Expose + private String documentNumber; - @Expose - private String legalName; - - @Expose - private DocumentType documentType; + @Expose + private String legalName; + + @Expose + private DocumentType documentType; - public Boolean isChargeTransferFees() { - return chargeTransferFees; - } - - public String getBankCode() { - return bankCode; - } - - public String getAgencia() { - return agencia; - } - - public String getAgenciaDv() { - return agenciaDv; - } - - public String getConta() { - return conta; - } - - public String getContaDv() { - return contaDv; - } - - public String getDocumentNumber() { - return documentNumber; - } - - public String getLegalName() { - return legalName; - } - - public DocumentType getDocumentType() { - return documentType; - } - - public void setBankCode(String bankCode) { - this.bankCode = bankCode; - addUnsavedProperty("bankCode"); - } - - public void setAgencia(String agencia) { - this.agencia = agencia; - addUnsavedProperty("agencia"); - } - - public void setAgenciaDv(String agenciaDv) { - this.agenciaDv = agenciaDv; - addUnsavedProperty("agenciaDv"); - } - - public void setConta(String conta) { - this.conta = conta; - addUnsavedProperty("conta"); - } - - public void setContaDv(String contaDv) { - this.contaDv = contaDv; - addUnsavedProperty("contaDv"); - } - - public void setDocumentNumber(String documentNumber) { - this.documentNumber = documentNumber; - addUnsavedProperty("documentNumber"); - } - - public void setLegalName(String legalName) { - this.legalName = legalName; - addUnsavedProperty("legalName"); - } - - public void setDocumentType(DocumentType documentType) { - this.documentType = documentType; - addUnsavedProperty("documentType"); - } - - public Collection findAll() throws PagarMeException { - return find(100, 0); - } - - public Collection find(int totalPerPage, int page) throws PagarMeException { - return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { - }.getType()); - } - - public BankAccount save() throws PagarMeException { - final BankAccount saved = super.save(BankAccount.class); - copy(saved); - - return saved; - } - - public BankAccount refresh() throws PagarMeException { - final BankAccount other = JsonUtils.getAsObject(refreshModel(), BankAccount.class); - copy(other); - flush(); - return other; - } - - public void copy(BankAccount other) { - setId(other.getId()); - this.chargeTransferFees = other.chargeTransferFees; - this.bankCode = other.bankCode; - this.agencia = other.agencia; - this.agenciaDv = other.agenciaDv; - this.conta = other.conta; - this.contaDv = other.contaDv; - this.documentNumber = other.documentNumber; - this.legalName = other.legalName; - this.documentType = other.documentType; - } - - public enum DocumentType { - @SerializedName("cpf") - CPF, - - @SerializedName("cnpj") - CNPJ - } + public Boolean isChargeTransferFees() { + return chargeTransferFees; + } + + public String getBankCode() { + return bankCode; + } + + public String getAgencia() { + return agencia; + } + + public String getAgenciaDv() { + return agenciaDv; + } + + public String getConta() { + return conta; + } + + public String getContaDv() { + return contaDv; + } + + public String getDocumentNumber() { + return documentNumber; + } + + public String getLegalName() { + return legalName; + } + + public DocumentType getDocumentType() { + return documentType; + } + + public void setBankCode(String bankCode) { + this.bankCode = bankCode; + addUnsavedProperty("bankCode"); + } + + public void setAgencia(String agencia) { + this.agencia = agencia; + addUnsavedProperty("agencia"); + } + + public void setAgenciaDv(String agenciaDv) { + this.agenciaDv = agenciaDv; + addUnsavedProperty("agenciaDv"); + } + + public void setConta(String conta) { + this.conta = conta; + addUnsavedProperty("conta"); + } + + public void setContaDv(String contaDv) { + this.contaDv = contaDv; + addUnsavedProperty("contaDv"); + } + + public void setDocumentNumber(String documentNumber) { + this.documentNumber = documentNumber; + addUnsavedProperty("documentNumber"); + } + + public void setLegalName(String legalName) { + this.legalName = legalName; + addUnsavedProperty("legalName"); + } + + public void setDocumentType(DocumentType documentType) { + this.documentType = documentType; + addUnsavedProperty("documentType"); + } + + public Collection findAll() throws PagarMeException { + return find(100, 0); + } + + public Collection find(int totalPerPage, int page) throws PagarMeException { + return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { + }.getType()); + } + + public BankAccount save() throws PagarMeException { + final BankAccount saved = super.save(BankAccount.class); + copy(saved); + + return saved; + } + + public BankAccount refresh() throws PagarMeException { + final BankAccount other = JsonUtils.getAsObject(refreshModel(), BankAccount.class); + copy(other); + flush(); + return other; + } + + public void copy(BankAccount other) { + setId(other.getId()); + this.chargeTransferFees = other.chargeTransferFees; + this.bankCode = other.bankCode; + this.agencia = other.agencia; + this.agenciaDv = other.agenciaDv; + this.conta = other.conta; + this.contaDv = other.contaDv; + this.documentNumber = other.documentNumber; + this.legalName = other.legalName; + this.documentType = other.documentType; + } + + public enum DocumentType { + @SerializedName("cpf") + CPF, + + @SerializedName("cnpj") + CNPJ + } } diff --git a/src/main/java/me/pagar/BulkAnticipation.java b/src/main/java/me/pagar/BulkAnticipation.java index a3ed065..b4fd25d 100644 --- a/src/main/java/me/pagar/BulkAnticipation.java +++ b/src/main/java/me/pagar/BulkAnticipation.java @@ -6,182 +6,182 @@ public class BulkAnticipation extends PagarMeModel { - @Expose(serialize = false) - private Integer amount; + @Expose(serialize = false) + private Integer amount; - @Expose(serialize = false) - private Integer anticipationFee; + @Expose(serialize = false) + private Integer anticipationFee; - /** - * Data de atualização da transação no formato ISODate - */ - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + /** + * Data de atualização da transação no formato ISODate + */ + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - @Expose(serialize = false) - private Integer fee; + @Expose(serialize = false) + private Integer fee; - @Expose - private DateTime paymentDate; + @Expose + private DateTime paymentDate; - @Expose(serialize = false) - private Status status; + @Expose(serialize = false) + private Status status; - @Expose - private Timeframe timeframe; + @Expose + private Timeframe timeframe; - @Expose(serialize = false) - private String type; + @Expose(serialize = false) + private String type; - @Expose(deserialize = false) - private Integer requestedAmount; + @Expose(deserialize = false) + private Integer requestedAmount; - @Expose(deserialize = false) - private Boolean building; + @Expose(deserialize = false) + private Boolean building; - public BulkAnticipation() { - super(); - } + public BulkAnticipation() { + super(); + } - public BulkAnticipation(final DateTime paymentDate, final Timeframe timeframe, final Integer requestedAmount, - final Boolean building) { - super(); - this.paymentDate = paymentDate; - this.timeframe = timeframe; - this.requestedAmount = requestedAmount; - this.building = building; - } + public BulkAnticipation(final DateTime paymentDate, final Timeframe timeframe, final Integer requestedAmount, + final Boolean building) { + super(); + this.paymentDate = paymentDate; + this.timeframe = timeframe; + this.requestedAmount = requestedAmount; + this.building = building; + } - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - public Integer getAnticipationFee() { - return anticipationFee; - } + public Integer getAnticipationFee() { + return anticipationFee; + } - public DateTime getUpdatedAt() { - return updatedAt; - } + public DateTime getUpdatedAt() { + return updatedAt; + } - public Integer getFee() { - return fee; - } + public Integer getFee() { + return fee; + } - public DateTime getPaymentDate() { - return paymentDate; - } + public DateTime getPaymentDate() { + return paymentDate; + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - public Timeframe getTimeframe() { - return timeframe; - } + public Timeframe getTimeframe() { + return timeframe; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setPaymentDate(final DateTime paymentDate) { - this.paymentDate = paymentDate; - } + public void setPaymentDate(final DateTime paymentDate) { + this.paymentDate = paymentDate; + } - public void setTimeframe(final Timeframe timeframe) { - this.timeframe = timeframe; - } + public void setTimeframe(final Timeframe timeframe) { + this.timeframe = timeframe; + } - public void setRequestedAmount(final Integer requestedAmount) { - this.requestedAmount = requestedAmount; - } + public void setRequestedAmount(final Integer requestedAmount) { + this.requestedAmount = requestedAmount; + } - public void setBuilding(final Boolean building) { - this.building = building; - } + public void setBuilding(final Boolean building) { + this.building = building; + } - @Override - public void setId(final String id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(final String id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(final String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(final String className) { + throw new UnsupportedOperationException("Not allowed."); + } - public static class Limits { + public static class Limits { - @Expose(serialize = false) - private Detail maximum; + @Expose(serialize = false) + private Detail maximum; - @Expose(serialize = false) - private Detail minimum; + @Expose(serialize = false) + private Detail minimum; - public Detail getMaximum() { - return maximum; - } + public Detail getMaximum() { + return maximum; + } - public Detail getMinimum() { - return minimum; - } + public Detail getMinimum() { + return minimum; + } - public static class Detail { + public static class Detail { - @Expose(serialize = false) - private Integer amount; + @Expose(serialize = false) + private Integer amount; - @Expose(serialize = false) - @SerializedName("anticipation_fee") - private Integer anticipationFee; + @Expose(serialize = false) + @SerializedName("anticipation_fee") + private Integer anticipationFee; - @Expose(serialize = false) - private Integer fee; + @Expose(serialize = false) + private Integer fee; - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - public Integer getAnticipationFee() { - return anticipationFee; - } + public Integer getAnticipationFee() { + return anticipationFee; + } - public Integer getFee() { - return fee; - } + public Integer getFee() { + return fee; + } - } + } - } + } - public enum Status { + public enum Status { - @SerializedName("approved") - APPROVED, + @SerializedName("approved") + APPROVED, - @SerializedName("building") - BUILDING, + @SerializedName("building") + BUILDING, - @SerializedName("canceled") - CANCELED, + @SerializedName("canceled") + CANCELED, - @SerializedName("pending") - PENDING, + @SerializedName("pending") + PENDING, - @SerializedName("refused") - REFUSED + @SerializedName("refused") + REFUSED - } + } - public enum Timeframe { + public enum Timeframe { - @SerializedName("end") - END, + @SerializedName("end") + END, - @SerializedName("start") - START + @SerializedName("start") + START - } + } } diff --git a/src/main/java/me/pagar/Card.java b/src/main/java/me/pagar/Card.java index 2df31b8..1569fcd 100644 --- a/src/main/java/me/pagar/Card.java +++ b/src/main/java/me/pagar/Card.java @@ -17,252 +17,252 @@ public class Card extends PagarMeModel { - private static final String TEMPLATE_ENCRYPT_QUERY = "card_number=%s&card_holder_name=%s&card_expiration_date=%s&card_cvv=%s\n"; + private static final String TEMPLATE_ENCRYPT_QUERY = "card_number=%s&card_holder_name=%s&card_expiration_date=%s&card_cvv=%s\n"; - @Expose(deserialize = false) - @SerializedName("card_hash") - private String hash; + @Expose(deserialize = false) + @SerializedName("card_hash") + private String hash; - @Expose(serialize = false) - private Brand brand; + @Expose(serialize = false) + private Brand brand; - @Expose - @SerializedName(value = "card_holder_name", alternate = {"holder_name"}) - private String holderName; + @Expose + @SerializedName(value = "card_holder_name", alternate = {"holder_name"}) + private String holderName; - @Expose(deserialize = false) - @SerializedName("card_number") - private String number; + @Expose(deserialize = false) + @SerializedName("card_number") + private String number; - @Expose(serialize = false) - private String firstDigits; + @Expose(serialize = false) + private String firstDigits; - @Expose(serialize = false) - private String lastDigits; + @Expose(serialize = false) + private String lastDigits; - @Expose(deserialize = false) - @SerializedName("card_cvv") - private String verificationValue; + @Expose(deserialize = false) + @SerializedName("card_cvv") + private String verificationValue; - @Expose(serialize = false) - private String fingerprint; + @Expose(serialize = false) + private String fingerprint; - @Expose(serialize = false) - private String country; + @Expose(serialize = false) + private String country; - @Expose(deserialize = false) - private Integer customerId; + @Expose(deserialize = false) + private Integer customerId; - @Expose(serialize = false) - private Boolean valid; + @Expose(serialize = false) + private Boolean valid; - @Expose - @SerializedName(value = "card_expiration_date", alternate = {"expiration_date"}) - private String expirationDate; + @Expose + @SerializedName(value = "card_expiration_date", alternate = {"expiration_date"}) + private String expirationDate; - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - @Expose(serialize = false) - private Customer customer; + @Expose(serialize = false) + private Customer customer; - public Card() { - super(); - } - - public Card(String id) { - this(); - setId(id); - } - - public Card(String number, String holderName, String expirationDate, String verificationValue) { - this(); - this.number = number; - this.holderName = holderName; - this.expirationDate = expirationDate; - this.verificationValue = verificationValue; - } - - public Brand getBrand() { - return brand; - } - - public String getHolderName() { - return holderName; - } - - public String getFirstDigits() { - return firstDigits; - } - - public String getLastDigits() { - return lastDigits; - } - - public String getVerificationValue() { - return verificationValue; - } - - public String getFingerprint() { - return fingerprint; - } - - public String getExpirationDate() { - return expirationDate; - } - - public String getCountry() { - return country; - } - - public Boolean getValid() { - return valid; - } - - public DateTime getUpdatedAt() { - return updatedAt; - } - - public Customer getCustomer() { - return customer; - } - - public void setHash(String hash) { - this.hash = hash; - addUnsavedProperty("hash"); - } - - public void setHolderName(String holderName) { - this.holderName = holderName; - addUnsavedProperty("holderName"); - } - - public void setNumber(String number) { - this.number = number; - addUnsavedProperty("number"); - } - - public void setVerificationValue(String verificationValue) { - this.verificationValue = verificationValue; - } - - public void setCustomerId(Integer customerId) { - this.customerId = customerId; - addUnsavedProperty("customerId"); - } - - public void setExpirationDate(String expirationDate) { - this.expirationDate = expirationDate; - addUnsavedProperty("expirationDate"); - } - - public String encrypt(CardHashKey cardHashKey) { - - if (Strings.isNullOrEmpty(number) || Strings.isNullOrEmpty(holderName) || - Strings.isNullOrEmpty(expirationDate) || Strings.isNullOrEmpty(verificationValue)) { - return hash; - } - - try { - final String publicKeyToken = cardHashKey.getPublicKey() - .replaceAll("\\n", "") - .replace("-----BEGIN PUBLIC KEY-----", "") - .replace("-----END PUBLIC KEY-----", ""); - final byte[] publicKeyBytes = Base64.decodeBase64(publicKeyToken); - final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes); - final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - final PublicKey publicKey = keyFactory.generatePublic(keySpec); - - final Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - - final String query = URLEncoder.encode(String.format(TEMPLATE_ENCRYPT_QUERY, - number, - holderName, - expirationDate, - verificationValue), "UTF-8"); - - hash = String.format("%d_%s", - cardHashKey.getId(), - Base64.encodeBase64String(cipher.doFinal(query.getBytes("UTF-8")))); - } catch (Exception e) { - hash = null; - } - - return hash; - } - - public Card save() throws PagarMeException { - final Card saved = super.save(getClass()); - copy(saved); - - return saved; - } - - /** - * @see #list(int, int) - */ - public Collection list() throws PagarMeException { - return list(100, 0); - } - - /** - * @param totalPerPage Retorna n objetos de transação - * @param page Útil para implementação de uma paginação de resultados - * @return Uma {@link Collection} contendo objetos de transações, ordenadas a partir da transação realizada mais - * recentemente. - * @throws PagarMeException - */ - public Collection list(int totalPerPage, int page) throws PagarMeException { - return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { - }.getType()); - } - - public Card refresh() throws PagarMeException { - final Card other = JsonUtils.getAsObject(refreshModel(), Card.class); - copy(other); - flush(); - return other; - } - - private void copy(Card other) { - setId(other.getId()); - this.brand = other.brand; - this.holderName = other.holderName; - this.firstDigits = other.firstDigits; - this.lastDigits = other.lastDigits; - this.fingerprint = other.fingerprint; - this.country = other.country; - this.valid = other.valid; - } - - public enum Brand { - - @SerializedName("amex") - AMEX, - - @SerializedName("aura") - AURA, - - @SerializedName("discover") - DISCOVER, - - @SerializedName("elo") - ELO, - - @SerializedName("hipercard") - HIPERCARD, - - @SerializedName("jcb") - JCB, - - @SerializedName("visa") - VISA, - - @SerializedName("mastercard") - MASTERCARD - - } + public Card() { + super(); + } + + public Card(String id) { + this(); + setId(id); + } + + public Card(String number, String holderName, String expirationDate, String verificationValue) { + this(); + this.number = number; + this.holderName = holderName; + this.expirationDate = expirationDate; + this.verificationValue = verificationValue; + } + + public Brand getBrand() { + return brand; + } + + public String getHolderName() { + return holderName; + } + + public String getFirstDigits() { + return firstDigits; + } + + public String getLastDigits() { + return lastDigits; + } + + public String getVerificationValue() { + return verificationValue; + } + + public String getFingerprint() { + return fingerprint; + } + + public String getExpirationDate() { + return expirationDate; + } + + public String getCountry() { + return country; + } + + public Boolean getValid() { + return valid; + } + + public DateTime getUpdatedAt() { + return updatedAt; + } + + public Customer getCustomer() { + return customer; + } + + public void setHash(String hash) { + this.hash = hash; + addUnsavedProperty("hash"); + } + + public void setHolderName(String holderName) { + this.holderName = holderName; + addUnsavedProperty("holderName"); + } + + public void setNumber(String number) { + this.number = number; + addUnsavedProperty("number"); + } + + public void setVerificationValue(String verificationValue) { + this.verificationValue = verificationValue; + } + + public void setCustomerId(Integer customerId) { + this.customerId = customerId; + addUnsavedProperty("customerId"); + } + + public void setExpirationDate(String expirationDate) { + this.expirationDate = expirationDate; + addUnsavedProperty("expirationDate"); + } + + public String encrypt(CardHashKey cardHashKey) { + + if (Strings.isNullOrEmpty(number) || Strings.isNullOrEmpty(holderName) || + Strings.isNullOrEmpty(expirationDate) || Strings.isNullOrEmpty(verificationValue)) { + return hash; + } + + try { + final String publicKeyToken = cardHashKey.getPublicKey() + .replaceAll("\\n", "") + .replace("-----BEGIN PUBLIC KEY-----", "") + .replace("-----END PUBLIC KEY-----", ""); + final byte[] publicKeyBytes = Base64.decodeBase64(publicKeyToken); + final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes); + final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + final PublicKey publicKey = keyFactory.generatePublic(keySpec); + + final Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + + final String query = URLEncoder.encode(String.format(TEMPLATE_ENCRYPT_QUERY, + number, + holderName, + expirationDate, + verificationValue), "UTF-8"); + + hash = String.format("%d_%s", + cardHashKey.getId(), + Base64.encodeBase64String(cipher.doFinal(query.getBytes("UTF-8")))); + } catch (Exception e) { + hash = null; + } + + return hash; + } + + public Card save() throws PagarMeException { + final Card saved = super.save(getClass()); + copy(saved); + + return saved; + } + + /** + * @see #list(int, int) + */ + public Collection list() throws PagarMeException { + return list(100, 0); + } + + /** + * @param totalPerPage Retorna n objetos de transação + * @param page Útil para implementação de uma paginação de resultados + * @return Uma {@link Collection} contendo objetos de transações, ordenadas a partir da transação realizada mais + * recentemente. + * @throws PagarMeException + */ + public Collection list(int totalPerPage, int page) throws PagarMeException { + return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { + }.getType()); + } + + public Card refresh() throws PagarMeException { + final Card other = JsonUtils.getAsObject(refreshModel(), Card.class); + copy(other); + flush(); + return other; + } + + private void copy(Card other) { + setId(other.getId()); + this.brand = other.brand; + this.holderName = other.holderName; + this.firstDigits = other.firstDigits; + this.lastDigits = other.lastDigits; + this.fingerprint = other.fingerprint; + this.country = other.country; + this.valid = other.valid; + } + + public enum Brand { + + @SerializedName("amex") + AMEX, + + @SerializedName("aura") + AURA, + + @SerializedName("discover") + DISCOVER, + + @SerializedName("elo") + ELO, + + @SerializedName("hipercard") + HIPERCARD, + + @SerializedName("jcb") + JCB, + + @SerializedName("visa") + VISA, + + @SerializedName("mastercard") + MASTERCARD + + } } diff --git a/src/main/java/me/pagar/CardHashKey.java b/src/main/java/me/pagar/CardHashKey.java index 442ea85..4757968 100644 --- a/src/main/java/me/pagar/CardHashKey.java +++ b/src/main/java/me/pagar/CardHashKey.java @@ -4,36 +4,36 @@ public class CardHashKey extends PagarMeModel { - @Expose(serialize = false) - private String ip; + @Expose(serialize = false) + private String ip; - @Expose(serialize = false) - private String publicKey; + @Expose(serialize = false) + private String publicKey; - public String getIp() { - return ip; - } + public String getIp() { + return ip; + } - public String getPublicKey() { - return publicKey; - } + public String getPublicKey() { + return publicKey; + } - public void setIp(String ip) { - this.ip = ip; - } + public void setIp(String ip) { + this.ip = ip; + } - public void setPublicKey(String publicKey) { - this.publicKey = publicKey; - } + public void setPublicKey(String publicKey) { + this.publicKey = publicKey; + } - @Override - public void setId(Integer id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(Integer id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } } diff --git a/src/main/java/me/pagar/Customer.java b/src/main/java/me/pagar/Customer.java index 1abda62..ca2acb8 100644 --- a/src/main/java/me/pagar/Customer.java +++ b/src/main/java/me/pagar/Customer.java @@ -11,163 +11,163 @@ public class Customer extends PagarMeModel { - @Expose - private String documentNumber; + @Expose + private String documentNumber; - @Expose(serialize = false) - private String documentType; + @Expose(serialize = false) + private String documentType; - @Expose - private String name; - - @Expose - private String email; - - @Expose - private String gender; + @Expose + private String name; + + @Expose + private String email; + + @Expose + private String gender; - @Expose - @SerializedName("born_at") - private LocalDate bornAt; + @Expose + @SerializedName("born_at") + private LocalDate bornAt; - @Expose(deserialize = false) - private Address address; + @Expose(deserialize = false) + private Address address; - @Expose(deserialize = false) - private Phone phone; - - @Expose(serialize = false) - private Collection
addresses; - - @Expose(serialize = false) - private Collection phones; - - public Customer() { - super(); - } - - public Customer(final String name, final String email) { - this(); - this.name = name; - this.email = email; - this.addresses = new ArrayList
(); - this.phones = new ArrayList(); - } - - public String getDocumentNumber() { - return documentNumber; - } - - public String getDocumentType() { - return documentType; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - public String getGender() { - return gender; - } - - public LocalDate getBornAt() { - return bornAt; - } - - public Collection getPhones() { - return phones; - } - - public Collection
getAddresses() { - return addresses; - } - - public void setDocumentNumber(final String documentNumber) { - this.documentNumber = documentNumber; - addUnsavedProperty("documentNumber"); - } - - public void setDocumentType(final String documentType) { - this.documentType = documentType; - addUnsavedProperty("documentType"); - } - - public void setName(final String name) { - this.name = name; - addUnsavedProperty("name"); - } - - public void setEmail(final String email) { - this.email = email; - addUnsavedProperty("email"); - } - - public void setGender(final String gender) { - this.gender = gender; - addUnsavedProperty("gender"); - } - - public void setBornAt(final LocalDate bornAt) { - this.bornAt = bornAt; - addUnsavedProperty("bornAt"); - } - - public void setAddress(Address address) { - this.address = address; - addUnsavedProperty("address"); - } - - public void setPhone(Phone phone) { - this.phone = phone; - addUnsavedProperty("phone"); - } - - public Customer save() throws PagarMeException { - final Customer saved = super.save(getClass()); - copy(saved); - - return saved; - } - - public Customer refresh() throws PagarMeException { - final Customer other = JsonUtils.getAsObject(refreshModel(), Customer.class); - copy(other); - flush(); - return other; - } - - private void copy(Customer other) { - setId(other.getId()); - this.documentNumber = other.documentNumber; - this.documentType = other.documentType; - this.name = other.name; - this.email = other.email; - this.gender = other.gender; - this.bornAt = other.bornAt; - this.addresses = other.addresses; - this.phones = other.phones; - } - - /** - * @see #list(int, int) - */ - public Collection list() throws PagarMeException { - return list(100, 0); - } - - /** - * @param totalPerPage - * @param page - * @return - * @throws PagarMeException - */ - public Collection list(int totalPerPage, int page) throws PagarMeException { - return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { - }.getType()); - } + @Expose(deserialize = false) + private Phone phone; + + @Expose(serialize = false) + private Collection
addresses; + + @Expose(serialize = false) + private Collection phones; + + public Customer() { + super(); + } + + public Customer(final String name, final String email) { + this(); + this.name = name; + this.email = email; + this.addresses = new ArrayList
(); + this.phones = new ArrayList(); + } + + public String getDocumentNumber() { + return documentNumber; + } + + public String getDocumentType() { + return documentType; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getGender() { + return gender; + } + + public LocalDate getBornAt() { + return bornAt; + } + + public Collection getPhones() { + return phones; + } + + public Collection
getAddresses() { + return addresses; + } + + public void setDocumentNumber(final String documentNumber) { + this.documentNumber = documentNumber; + addUnsavedProperty("documentNumber"); + } + + public void setDocumentType(final String documentType) { + this.documentType = documentType; + addUnsavedProperty("documentType"); + } + + public void setName(final String name) { + this.name = name; + addUnsavedProperty("name"); + } + + public void setEmail(final String email) { + this.email = email; + addUnsavedProperty("email"); + } + + public void setGender(final String gender) { + this.gender = gender; + addUnsavedProperty("gender"); + } + + public void setBornAt(final LocalDate bornAt) { + this.bornAt = bornAt; + addUnsavedProperty("bornAt"); + } + + public void setAddress(Address address) { + this.address = address; + addUnsavedProperty("address"); + } + + public void setPhone(Phone phone) { + this.phone = phone; + addUnsavedProperty("phone"); + } + + public Customer save() throws PagarMeException { + final Customer saved = super.save(getClass()); + copy(saved); + + return saved; + } + + public Customer refresh() throws PagarMeException { + final Customer other = JsonUtils.getAsObject(refreshModel(), Customer.class); + copy(other); + flush(); + return other; + } + + private void copy(Customer other) { + setId(other.getId()); + this.documentNumber = other.documentNumber; + this.documentType = other.documentType; + this.name = other.name; + this.email = other.email; + this.gender = other.gender; + this.bornAt = other.bornAt; + this.addresses = other.addresses; + this.phones = other.phones; + } + + /** + * @see #list(int, int) + */ + public Collection list() throws PagarMeException { + return list(100, 0); + } + + /** + * @param totalPerPage + * @param page + * @return + * @throws PagarMeException + */ + public Collection list(int totalPerPage, int page) throws PagarMeException { + return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { + }.getType()); + } } diff --git a/src/main/java/me/pagar/PagarMe.java b/src/main/java/me/pagar/PagarMe.java index 8b1b4f9..f3bca8c 100644 --- a/src/main/java/me/pagar/PagarMe.java +++ b/src/main/java/me/pagar/PagarMe.java @@ -8,77 +8,94 @@ public abstract class PagarMe { - public static final String ENDPOINT = "https://api.pagar.me"; + public static final String ENDPOINT = "https://api.pagar.me"; - public static final String API_VERSION = "1"; + public static final String API_VERSION = "1"; - public static final String HMAC_MD5_ALGORITHM = "HmacMD5"; + public static final String HMAC_MD5_ALGORITHM = "HmacMD5"; - public static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; + public static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; - public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; + public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; - public static final String SHA1_ALGORITHM = "sha1"; + public static final String SHA1_ALGORITHM = "sha1"; - public static final String SHA256_ALGORITHM = "sha256"; + public static final String SHA256_ALGORITHM = "sha256"; - private static String apiKey; + private static String apiKey; - public static String fullApiUrl(final String path) { - return ENDPOINT.concat("/") - .concat(API_VERSION) - .concat(path); - } + private static boolean sslPinningEnabled; - public static String getApiKey() { - return apiKey; - } + public static String fullApiUrl(final String path) { + return ENDPOINT.concat("/") + .concat(API_VERSION) + .concat(path); + } - public static void init(String apiKey) { - PagarMe.apiKey = apiKey; - } + public static String getApiKey() { + return apiKey; + } - public static boolean validateRequestSignature(final String payload, final String signature) { + public static boolean isSslPinningEnabled() { + return sslPinningEnabled; + } - // failsafe - if (Strings.isNullOrEmpty(signature)) { - return true; - } + public static void init(String apiKey) { + init(apiKey, true); + } - final String[] parts = signature.split("="); + /** + * Configura o cliente padrão para comunicação com a API. + * + * @param apiKey API Key disponível no dashboard + * @param sslPinningEnabled Valida o certificado SSL do host com o embarcado na biblioteca + */ + public static void init(String apiKey, boolean sslPinningEnabled) { + PagarMe.apiKey = apiKey; + PagarMe.sslPinningEnabled = sslPinningEnabled; + } - try { - // get an hmac_sha1 key from the raw key bytes - final SecretKeySpec signingKey = new SecretKeySpec(apiKey.getBytes(), parts[0]); + public static boolean validateRequestSignature(final String payload, final String signature) { - String algorithm = HMAC_MD5_ALGORITHM; + // failsafe + if (Strings.isNullOrEmpty(signature)) { + return true; + } - if (parts[0].equalsIgnoreCase(SHA1_ALGORITHM)) { - algorithm = HMAC_SHA1_ALGORITHM; - } else if (parts[0].equalsIgnoreCase(SHA256_ALGORITHM)) { - algorithm = HMAC_SHA256_ALGORITHM; - } + final String[] parts = signature.split("="); - // get an hmac_sha1 Mac instance and initialize with the signing key - final Mac mac = Mac.getInstance(algorithm); - mac.init(signingKey); + try { + // get an hmac_sha1 key from the raw key bytes + final SecretKeySpec signingKey = new SecretKeySpec(apiKey.getBytes(), parts[0]); - // compute the hmac on input data bytes - final byte[] rawHmac = mac.doFinal(payload.getBytes()); + String algorithm = HMAC_MD5_ALGORITHM; - final Formatter formatter = new Formatter(); + if (parts[0].equalsIgnoreCase(SHA1_ALGORITHM)) { + algorithm = HMAC_SHA1_ALGORITHM; + } else if (parts[0].equalsIgnoreCase(SHA256_ALGORITHM)) { + algorithm = HMAC_SHA256_ALGORITHM; + } - // right transform into sha1 hash - for (byte b : rawHmac) { - formatter.format("%02x", 0xff & b); - } + // get an hmac_sha1 Mac instance and initialize with the signing key + final Mac mac = Mac.getInstance(algorithm); + mac.init(signingKey); - final String hash = formatter.toString(); - formatter.close(); + // compute the hmac on input data bytes + final byte[] rawHmac = mac.doFinal(payload.getBytes()); - return (parts.length == 2) && (hash.equals(parts[1])); - } catch (Exception e) { - return false; - } - } + final Formatter formatter = new Formatter(); + + // right transform into sha1 hash + for (byte b : rawHmac) { + formatter.format("%02x", 0xff & b); + } + + final String hash = formatter.toString(); + formatter.close(); + + return (parts.length == 2) && (hash.equals(parts[1])); + } catch (Exception e) { + return false; + } + } } diff --git a/src/main/java/me/pagar/PagarMeError.java b/src/main/java/me/pagar/PagarMeError.java index 6322e45..a44e54f 100644 --- a/src/main/java/me/pagar/PagarMeError.java +++ b/src/main/java/me/pagar/PagarMeError.java @@ -5,31 +5,31 @@ public class PagarMeError { - private String parameterName; + private String parameterName; - private String type; + private String type; - private String message; + private String message; - private static String safeValue(JsonElement value) { - return (null == value || value.isJsonNull() ? null : value.getAsString()); - } + private static String safeValue(JsonElement value) { + return (null == value || value.isJsonNull() ? null : value.getAsString()); + } - public PagarMeError(JsonObject error) { - this.parameterName = safeValue(error.get("parameter_name")); - this.type = safeValue(error.get("type")); - this.message = safeValue(error.get("message")); - } + public PagarMeError(JsonObject error) { + this.parameterName = safeValue(error.get("parameter_name")); + this.type = safeValue(error.get("type")); + this.message = safeValue(error.get("message")); + } - public String getParameterName() { - return parameterName; - } + public String getParameterName() { + return parameterName; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } } diff --git a/src/main/java/me/pagar/PagarMeException.java b/src/main/java/me/pagar/PagarMeException.java index b8b1c28..903e873 100644 --- a/src/main/java/me/pagar/PagarMeException.java +++ b/src/main/java/me/pagar/PagarMeException.java @@ -9,90 +9,90 @@ public class PagarMeException extends Exception { - private int returnCode; + private int returnCode; - private String url; + private String url; - private String method; + private String method; - private String parameterMap; + private String parameterMap; - private String type; + private String type; - Collection errors = new ArrayList(); + Collection errors = new ArrayList(); - public static PagarMeException buildWithError(final Exception error) { - return new PagarMeException(error.getMessage(), null); - } + public static PagarMeException buildWithError(final Exception error) { + return new PagarMeException(error.getMessage(), null); + } - @SuppressWarnings("unchecked") - public static PagarMeException buildWithError(final PagarMeResponse response) { + @SuppressWarnings("unchecked") + public static PagarMeException buildWithError(final PagarMeResponse response) { - if (null == response) - return null; + if (null == response) + return null; - final JsonObject responseError = JsonUtils.getInterpreter().fromJson(response.getBody(), JsonObject.class); + final JsonObject responseError = JsonUtils.getInterpreter().fromJson(response.getBody(), JsonObject.class); - final JsonArray errors = responseError.getAsJsonArray("errors"); + final JsonArray errors = responseError.getAsJsonArray("errors"); - final StringBuilder joinedMessages = new StringBuilder(); + final StringBuilder joinedMessages = new StringBuilder(); - for (int i = 0; i < errors.size(); i++) { - final JsonObject error = errors.get(i).getAsJsonObject(); - joinedMessages - .append(error.get("message").getAsString()) - .append("\n"); - } + for (int i = 0; i < errors.size(); i++) { + final JsonObject error = errors.get(i).getAsJsonObject(); + joinedMessages + .append(error.get("message").getAsString()) + .append("\n"); + } - final PagarMeException exception = new PagarMeException(joinedMessages.toString(), responseError); - exception.returnCode = response.getCode(); + final PagarMeException exception = new PagarMeException(joinedMessages.toString(), responseError); + exception.returnCode = response.getCode(); - return exception; - } + return exception; + } - public PagarMeException(int returnCode, String url, String method, String message) { - super(message); - this.returnCode = returnCode; - this.url = url; - this.method = method; - } + public PagarMeException(int returnCode, String url, String method, String message) { + super(message); + this.returnCode = returnCode; + this.url = url; + this.method = method; + } - public PagarMeException(final String message) { - this(message, null); - } + public PagarMeException(final String message) { + this(message, null); + } - @SuppressWarnings("unchecked") - public PagarMeException(final String message, final JsonObject responseError) { - super(message); + @SuppressWarnings("unchecked") + public PagarMeException(final String message, final JsonObject responseError) { + super(message); - if (null == responseError || !responseError.has("errors")) - return; + if (null == responseError || !responseError.has("errors")) + return; - this.url = responseError.get("url").getAsString(); - this.method = responseError.get("method").getAsString(); + this.url = responseError.get("url").getAsString(); + this.method = responseError.get("method").getAsString(); - final JsonArray errors = responseError.get("errors").getAsJsonArray(); + final JsonArray errors = responseError.get("errors").getAsJsonArray(); - for (int i = 0; i < errors.size(); i++) { - final JsonObject error = errors.get(i).getAsJsonObject(); - this.errors.add(new PagarMeError(error)); - } - } + for (int i = 0; i < errors.size(); i++) { + final JsonObject error = errors.get(i).getAsJsonObject(); + this.errors.add(new PagarMeError(error)); + } + } - public Collection getErrors() { - return errors; - } + public Collection getErrors() { + return errors; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public String getMethod() { - return method; - } + public String getMethod() { + return method; + } - public int getReturnCode() { - return returnCode; - } + public int getReturnCode() { + return returnCode; + } } diff --git a/src/main/java/me/pagar/PagarMeModel.java b/src/main/java/me/pagar/PagarMeModel.java index f7fcbf7..c55f772 100644 --- a/src/main/java/me/pagar/PagarMeModel.java +++ b/src/main/java/me/pagar/PagarMeModel.java @@ -26,215 +26,215 @@ */ public abstract class PagarMeModel { - /** - * Número identificador da transação - */ - @Expose(serialize = false) - @SerializedName("id") - private PK id; - - /** - * Data de criação da transação no formato ISODate - */ - @Expose(serialize = false) - @SerializedName("date_created") - private DateTime createdAt; - - /** - * Nome da classe no plural, lower case e undesrcored. - */ - private transient String className; - - /** - * {@link Collection} de atributos que tiveram seus valores alterados. - */ - private transient Collection dirtyProperties; - - /** - * Valida se o atributo {@link #id} foi preenchido. - */ - protected void validateId() { - - if (getId() == null) { - throw new IllegalArgumentException("The Object ID must be set in order to use this method."); - } - - } - - public PagarMeModel() { - className = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, English.plural(getClass().getSimpleName())); - dirtyProperties = new ArrayList(); - } - - /** - * {@link #id} - */ - public PK getId() { - return id; - } - - /** - * {@link #createdAt} - */ - public DateTime getCreatedAt() { - return createdAt; - } - - /** - * {@link #className} - */ - public String getClassName() { - return className; - } - - public void setId(final PK id) { - this.id = id; - } - - public void setClassName(final String className) { - this.className = className; - } - - /** - * Atualiza o estado do modelo - * - * @return A representação atualizada do estado do modelo - * @throws PagarMeException - */ - protected JsonObject refreshModel() throws PagarMeException { - return get(this.id); - } - - /** - * Obtem um modelo pelo id. - * - * @param id Identificação do Modelo - * @return A representação do estado do modelo - * @throws PagarMeException - */ - protected JsonObject get(final PK id) throws PagarMeException { - validateId(); - return new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", className, id)).execute(); - } - - /** - * @param totalPerPage - * @return - * @throws PagarMeException - */ - protected JsonArray paginate(final Integer totalPerPage) throws PagarMeException { - return paginate(totalPerPage, 1); - } - - /** - * @param totalPerPage - * @param page - * @return - * @throws PagarMeException - */ - protected JsonArray paginate(final Integer totalPerPage, Integer page) throws PagarMeException { - final Map parameters = new HashMap(); - - if (null != totalPerPage && 0 != totalPerPage) { - parameters.put("count", totalPerPage); - } - - if (null == page || 0 >= page) { - page = 1; - } - - parameters.put("page", page); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s", className)); - request.getParameters().putAll(parameters); - - return request.execute(); - } - - /** - * Persiste o estado do modelo no servidor. - * - * @param clazz {@link Class} do Modelo - * @param Classe do Modelo - * @return O Modelo com os dados persistidos no servidor. - * @throws PagarMeException - */ - protected T save(final Class clazz) throws PagarMeException { - - if (!beforeSave()) { - return null; - } - - final PagarMeRequest request = null == id ? - new PagarMeRequest(HttpMethod.POST, String.format("/%s", className)) : - new PagarMeRequest(HttpMethod.PUT, String.format("/%s/%s/", className, id)); - request.setParameters(JsonUtils.objectToMap(this)); - - final JsonElement element = request.execute(); - flush(); - - return JsonUtils.getAsObject((JsonObject) element, clazz); - } - - /** - * Atualiza lista de atributos alterados. - * - * @param name Nome do atributo - */ - protected void addUnsavedProperty(final String name) { - for (String s : dirtyProperties) { - if (s.startsWith(name.concat("."))) { - dirtyProperties.remove(s); - } - } - dirtyProperties.add(name); - } - - /** - * Limpa lista de atributos com dados alterados. - */ - protected void flush() { - dirtyProperties.clear(); - } - - /** - * Callback para validação de modelo no método {@link #save(Class)}. - * - * @return true para persistir os dados; false para não persistir - */ - protected boolean beforeSave() { - return true; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final PagarMeModel that = (PagarMeModel) o; - - return id.equals(that.id); - - } - - @Override - public int hashCode() { - return id.hashCode(); - } - - @Override - public String toString() { - try { - return new GsonBuilder() - .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) - .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) - .registerTypeAdapter(BulkAnticipation.class, new BulkAnticipationAdapter()) - .setLongSerializationPolicy(LongSerializationPolicy.STRING) - .create() - .toJson(this); - } catch (UnsupportedOperationException e) { - return getClass().getSimpleName().concat(String.format("=(%s)", this.id)); - } - } + /** + * Número identificador da transação + */ + @Expose(serialize = false) + @SerializedName("id") + private PK id; + + /** + * Data de criação da transação no formato ISODate + */ + @Expose(serialize = false) + @SerializedName("date_created") + private DateTime createdAt; + + /** + * Nome da classe no plural, lower case e undesrcored. + */ + private transient String className; + + /** + * {@link Collection} de atributos que tiveram seus valores alterados. + */ + private transient Collection dirtyProperties; + + /** + * Valida se o atributo {@link #id} foi preenchido. + */ + protected void validateId() { + + if (getId() == null) { + throw new IllegalArgumentException("The Object ID must be set in order to use this method."); + } + + } + + public PagarMeModel() { + className = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, English.plural(getClass().getSimpleName())); + dirtyProperties = new ArrayList(); + } + + /** + * {@link #id} + */ + public PK getId() { + return id; + } + + /** + * {@link #createdAt} + */ + public DateTime getCreatedAt() { + return createdAt; + } + + /** + * {@link #className} + */ + public String getClassName() { + return className; + } + + public void setId(final PK id) { + this.id = id; + } + + public void setClassName(final String className) { + this.className = className; + } + + /** + * Atualiza o estado do modelo + * + * @return A representação atualizada do estado do modelo + * @throws PagarMeException + */ + protected JsonObject refreshModel() throws PagarMeException { + return get(this.id); + } + + /** + * Obtem um modelo pelo id. + * + * @param id Identificação do Modelo + * @return A representação do estado do modelo + * @throws PagarMeException + */ + protected JsonObject get(final PK id) throws PagarMeException { + validateId(); + return new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", className, id)).execute(); + } + + /** + * @param totalPerPage + * @return + * @throws PagarMeException + */ + protected JsonArray paginate(final Integer totalPerPage) throws PagarMeException { + return paginate(totalPerPage, 1); + } + + /** + * @param totalPerPage + * @param page + * @return + * @throws PagarMeException + */ + protected JsonArray paginate(final Integer totalPerPage, Integer page) throws PagarMeException { + final Map parameters = new HashMap(); + + if (null != totalPerPage && 0 != totalPerPage) { + parameters.put("count", totalPerPage); + } + + if (null == page || 0 >= page) { + page = 1; + } + + parameters.put("page", page); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s", className)); + request.getParameters().putAll(parameters); + + return request.execute(); + } + + /** + * Persiste o estado do modelo no servidor. + * + * @param clazz {@link Class} do Modelo + * @param Classe do Modelo + * @return O Modelo com os dados persistidos no servidor. + * @throws PagarMeException + */ + protected T save(final Class clazz) throws PagarMeException { + + if (!beforeSave()) { + return null; + } + + final PagarMeRequest request = null == id ? + new PagarMeRequest(HttpMethod.POST, String.format("/%s", className)) : + new PagarMeRequest(HttpMethod.PUT, String.format("/%s/%s/", className, id)); + request.setParameters(JsonUtils.objectToMap(this)); + + final JsonElement element = request.execute(); + flush(); + + return JsonUtils.getAsObject((JsonObject) element, clazz); + } + + /** + * Atualiza lista de atributos alterados. + * + * @param name Nome do atributo + */ + protected void addUnsavedProperty(final String name) { + for (String s : dirtyProperties) { + if (s.startsWith(name.concat("."))) { + dirtyProperties.remove(s); + } + } + dirtyProperties.add(name); + } + + /** + * Limpa lista de atributos com dados alterados. + */ + protected void flush() { + dirtyProperties.clear(); + } + + /** + * Callback para validação de modelo no método {@link #save(Class)}. + * + * @return true para persistir os dados; false para não persistir + */ + protected boolean beforeSave() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final PagarMeModel that = (PagarMeModel) o; + + return id.equals(that.id); + + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public String toString() { + try { + return new GsonBuilder() + .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) + .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) + .registerTypeAdapter(BulkAnticipation.class, new BulkAnticipationAdapter()) + .setLongSerializationPolicy(LongSerializationPolicy.STRING) + .create() + .toJson(this); + } catch (UnsupportedOperationException e) { + return getClass().getSimpleName().concat(String.format("=(%s)", this.id)); + } + } } diff --git a/src/main/java/me/pagar/PagarMeRequest.java b/src/main/java/me/pagar/PagarMeRequest.java index 4799492..a812a59 100644 --- a/src/main/java/me/pagar/PagarMeRequest.java +++ b/src/main/java/me/pagar/PagarMeRequest.java @@ -9,53 +9,53 @@ public class PagarMeRequest extends PagarMe { - private final String path; + private final String path; - private final String method; + private final String method; - private final boolean live; + private final boolean live; - private Map parameters; + private Map parameters; - private Map headers; + private Map headers; - public PagarMeRequest(String method, String path) { - this(method, path, true); - } + public PagarMeRequest(String method, String path) { + this(method, path, true); + } - public PagarMeRequest(String method, String path, boolean live) { - this.path = path; - this.method = method; - this.live = live; - this.parameters = new HashMap(); - } + public PagarMeRequest(String method, String path, boolean live) { + this.path = path; + this.method = method; + this.live = live; + this.parameters = new HashMap(); + } - @SuppressWarnings("unchecked") - public T execute() throws PagarMeException { + @SuppressWarnings("unchecked") + public T execute() throws PagarMeException { - if (Strings.isNullOrEmpty(getApiKey())) { - throw new PagarMeException("You need to configure API key before performing requests."); - } + if (Strings.isNullOrEmpty(getApiKey())) { + throw new PagarMeException("You need to configure API key before performing requests."); + } - final RestClient client = new RestClient(method, fullApiUrl(path), parameters, headers); - final PagarMeResponse response = client.execute(); + final RestClient client = new RestClient(method, fullApiUrl(path), parameters, headers); + final PagarMeResponse response = client.execute(); - final JsonElement decoded = JsonUtils.getInterpreter().fromJson(response.getBody(), JsonElement.class); + final JsonElement decoded = JsonUtils.getInterpreter().fromJson(response.getBody(), JsonElement.class); - if (response.getCode() == 200) { - return (T) decoded; - } else { - throw PagarMeException.buildWithError(response); - } + if (response.getCode() == 200) { + return (T) decoded; + } else { + throw PagarMeException.buildWithError(response); + } - } + } - public Map getParameters() { - return parameters; - } + public Map getParameters() { + return parameters; + } - public void setParameters(Map parameters) { - this.parameters = parameters; - } + public void setParameters(Map parameters) { + this.parameters = parameters; + } } diff --git a/src/main/java/me/pagar/PagarMeResponse.java b/src/main/java/me/pagar/PagarMeResponse.java index 0667b0b..2d30b1e 100644 --- a/src/main/java/me/pagar/PagarMeResponse.java +++ b/src/main/java/me/pagar/PagarMeResponse.java @@ -5,30 +5,30 @@ public class PagarMeResponse { - private int code = -1; + private int code = -1; - private final JsonElement body; + private final JsonElement body; - public PagarMeResponse(final JsonElement body) { - this.body = body; - } + public PagarMeResponse(final JsonElement body) { + this.body = body; + } - public PagarMeResponse(final int code, final JsonElement body) { - this.code = code; - this.body = body; - } + public PagarMeResponse(final int code, final JsonElement body) { + this.code = code; + this.body = body; + } - public PagarMeResponse(final JsonObject object) { - this.code = object.get("code").getAsInt(); - this.body = object.get("body"); - } + public PagarMeResponse(final JsonObject object) { + this.code = object.get("code").getAsInt(); + this.body = object.get("body"); + } - public int getCode() { - return code; - } + public int getCode() { + return code; + } - public JsonElement getBody() { - return body; - } + public JsonElement getBody() { + return body; + } } diff --git a/src/main/java/me/pagar/Payable.java b/src/main/java/me/pagar/Payable.java index f4a82d2..4633966 100644 --- a/src/main/java/me/pagar/Payable.java +++ b/src/main/java/me/pagar/Payable.java @@ -14,94 +14,94 @@ */ public class Payable extends PagarMeModel { - @Expose(serialize = false) - private Integer amount; + @Expose(serialize = false) + private Integer amount; - @Expose(serialize = false) - private Integer fee; + @Expose(serialize = false) + private Integer fee; - @Expose(serialize = false) - private Integer installment; + @Expose(serialize = false) + private Integer installment; - @Expose(serialize = false) - private Integer transactionId; + @Expose(serialize = false) + private Integer transactionId; - @Expose(serialize = false) - private String splitRuleId; + @Expose(serialize = false) + private String splitRuleId; - @Expose(serialize = false) - @SerializedName("payment_date") - private DateTime payment; + @Expose(serialize = false) + @SerializedName("payment_date") + private DateTime payment; - @Expose(serialize = false) - private Status status; + @Expose(serialize = false) + private Status status; - @Expose(serialize = false) - private Type type; + @Expose(serialize = false) + private Type type; - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - public Integer getFee() { - return fee; - } + public Integer getFee() { + return fee; + } - public Integer getInstallment() { - return installment; - } + public Integer getInstallment() { + return installment; + } - public Integer getTransactionId() { - return transactionId; - } + public Integer getTransactionId() { + return transactionId; + } - public String getSplitRuleId() { - return splitRuleId; - } + public String getSplitRuleId() { + return splitRuleId; + } - public DateTime getPayment() { - return payment; - } + public DateTime getPayment() { + return payment; + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - public Type getType() { - return type; - } + public Type getType() { + return type; + } - @Override - public void setId(Integer id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(Integer id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } - public enum Status { + public enum Status { - @SerializedName("paid") - PAID, + @SerializedName("paid") + PAID, - @SerializedName("waiting_funds") - WAITING_FUNDS + @SerializedName("waiting_funds") + WAITING_FUNDS - } + } - public enum Type { + public enum Type { - @SerializedName("chargeback") - CHARGEBACK, + @SerializedName("chargeback") + CHARGEBACK, - @SerializedName("credit") - CREDIT, + @SerializedName("credit") + CREDIT, - @SerializedName("refund") - REFUND + @SerializedName("refund") + REFUND - } + } } diff --git a/src/main/java/me/pagar/Phone.java b/src/main/java/me/pagar/Phone.java index c390722..bcfddeb 100644 --- a/src/main/java/me/pagar/Phone.java +++ b/src/main/java/me/pagar/Phone.java @@ -6,65 +6,65 @@ public class Phone extends PagarMeModel { - @Expose - private String ddi; - - @Expose - private String ddd; - - @Expose - private String number; - - public Phone() { - super(); - } - - public Phone(final String ddd, final String number) { - this(); - this.ddd = ddd; - this.number = number; - } - - public String getDdi() { - return ddi; - } - - public String getDdd() { - return ddd; - } - - public String getNumber() { - return number; - } - - @Override - public DateTime getCreatedAt() { - throw new UnsupportedOperationException("Not allowed."); - } - - public void setDdi(final String ddi) { - this.ddi = ddi; - addUnsavedProperty("ddi"); - } - - public void setDdd(final String ddd) { - this.ddd = ddd; - addUnsavedProperty("ddd"); - } - - public void setNumber(final String number) { - this.number = number; - addUnsavedProperty("number"); - } - - @Override - public void setId(Integer id) { - throw new UnsupportedOperationException("Not allowed."); - } - - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Expose + private String ddi; + + @Expose + private String ddd; + + @Expose + private String number; + + public Phone() { + super(); + } + + public Phone(final String ddd, final String number) { + this(); + this.ddd = ddd; + this.number = number; + } + + public String getDdi() { + return ddi; + } + + public String getDdd() { + return ddd; + } + + public String getNumber() { + return number; + } + + @Override + public DateTime getCreatedAt() { + throw new UnsupportedOperationException("Not allowed."); + } + + public void setDdi(final String ddi) { + this.ddi = ddi; + addUnsavedProperty("ddi"); + } + + public void setDdd(final String ddd) { + this.ddd = ddd; + addUnsavedProperty("ddd"); + } + + public void setNumber(final String number) { + this.number = number; + addUnsavedProperty("number"); + } + + @Override + public void setId(Integer id) { + throw new UnsupportedOperationException("Not allowed."); + } + + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } } diff --git a/src/main/java/me/pagar/Postback.java b/src/main/java/me/pagar/Postback.java index 770a920..71cbd3c 100644 --- a/src/main/java/me/pagar/Postback.java +++ b/src/main/java/me/pagar/Postback.java @@ -8,151 +8,151 @@ public class Postback extends PagarMeModel { - @Expose(serialize = false) - private Integer retries; + @Expose(serialize = false) + private Integer retries; - @Expose(serialize = false) - private String headers; + @Expose(serialize = false) + private String headers; - @Expose(serialize = false) - private String model; + @Expose(serialize = false) + private String model; - @Expose(serialize = false) - private String modelId; + @Expose(serialize = false) + private String modelId; - @Expose(serialize = false) - private String nextRetry; // ??? + @Expose(serialize = false) + private String nextRetry; // ??? - @Expose(serialize = false) - private String payload; + @Expose(serialize = false) + private String payload; - @Expose(serialize = false) - private String requestUrl; + @Expose(serialize = false) + private String requestUrl; - @Expose(serialize = false) - private String signature; + @Expose(serialize = false) + private String signature; - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - @Expose(serialize = false) - private Collection deliveries; + @Expose(serialize = false) + private Collection deliveries; - @Expose(serialize = false) - private Transaction.Status status; + @Expose(serialize = false) + private Transaction.Status status; - public Integer getRetries() { - return retries; - } + public Integer getRetries() { + return retries; + } - public String getHeaders() { - return headers; - } + public String getHeaders() { + return headers; + } - public String getModel() { - return model; - } + public String getModel() { + return model; + } - public String getModelId() { - return modelId; - } + public String getModelId() { + return modelId; + } - public String getNextRetry() { - return nextRetry; - } + public String getNextRetry() { + return nextRetry; + } - public String getPayload() { - return payload; - } + public String getPayload() { + return payload; + } - public String getRequestUrl() { - return requestUrl; - } + public String getRequestUrl() { + return requestUrl; + } - public String getSignature() { - return signature; - } + public String getSignature() { + return signature; + } - public DateTime getUpdatedAt() { - return updatedAt; - } + public DateTime getUpdatedAt() { + return updatedAt; + } - public Transaction.Status getStatus() { - return status; - } + public Transaction.Status getStatus() { + return status; + } - public Collection getDeliveries() { - return deliveries; - } + public Collection getDeliveries() { + return deliveries; + } - @Override - public void setId(String id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(String id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } - public static class PostbackDelivery { + public static class PostbackDelivery { - @Expose(serialize = false) - @SerializedName("response_time") - private Integer responseTime; + @Expose(serialize = false) + @SerializedName("response_time") + private Integer responseTime; - @Expose(serialize = false) - @SerializedName("response_body") - private String responseBody; + @Expose(serialize = false) + @SerializedName("response_body") + private String responseBody; - @Expose(serialize = false) - @SerializedName("response_headers") - private String responseHeaders; + @Expose(serialize = false) + @SerializedName("response_headers") + private String responseHeaders; - @Expose(serialize = false) - @SerializedName("status_code") - private String statusCode; + @Expose(serialize = false) + @SerializedName("status_code") + private String statusCode; - @Expose(serialize = false) - @SerializedName("status_reason") - private String statusReason; + @Expose(serialize = false) + @SerializedName("status_reason") + private String statusReason; - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - @Expose(serialize = false) - private Transaction.Status status; + @Expose(serialize = false) + private Transaction.Status status; - public Integer getResponseTime() { - return responseTime; - } + public Integer getResponseTime() { + return responseTime; + } - public String getResponseBody() { - return responseBody; - } + public String getResponseBody() { + return responseBody; + } - public String getResponseHeaders() { - return responseHeaders; - } + public String getResponseHeaders() { + return responseHeaders; + } - public String getStatusCode() { - return statusCode; - } + public String getStatusCode() { + return statusCode; + } - public String getStatusReason() { - return statusReason; - } + public String getStatusReason() { + return statusReason; + } - public DateTime getUpdatedAt() { - return updatedAt; - } + public DateTime getUpdatedAt() { + return updatedAt; + } - public Transaction.Status getStatus() { - return status; - } + public Transaction.Status getStatus() { + return status; + } - } + } } diff --git a/src/main/java/me/pagar/Recipient.java b/src/main/java/me/pagar/Recipient.java index fb8d5d2..ddae002 100644 --- a/src/main/java/me/pagar/Recipient.java +++ b/src/main/java/me/pagar/Recipient.java @@ -13,250 +13,250 @@ public class Recipient extends PagarMeModel { - @Expose(serialize = false) - private Boolean automaticAnticipationEnabled; + @Expose(serialize = false) + private Boolean automaticAnticipationEnabled; - @Expose - private Boolean transferEnabled; + @Expose + private Boolean transferEnabled; - @Expose(serialize = false) - private Integer anticipatableVolumePercentage; + @Expose(serialize = false) + private Integer anticipatableVolumePercentage; - @Expose - private Integer transferDay; + @Expose + private Integer transferDay; - @Expose(deserialize = false) - private Integer bankAccountId; + @Expose(deserialize = false) + private Integer bankAccountId; - @Expose - private BankAccount bankAccount; + @Expose + private BankAccount bankAccount; - @Expose - private TransferInterval transferInterval; + @Expose + private TransferInterval transferInterval; - @Expose(serialize = false) - private DateTime lastTransfer; - - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + private DateTime lastTransfer; + + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - public Boolean isAutomaticAnticipationEnabled() { - return automaticAnticipationEnabled; - } + public Boolean isAutomaticAnticipationEnabled() { + return automaticAnticipationEnabled; + } - public Boolean isTransferEnabled() { - return transferEnabled; - } + public Boolean isTransferEnabled() { + return transferEnabled; + } - public Integer getAnticipatableVolumePercentage() { - return anticipatableVolumePercentage; - } - - public Integer getTransferDay() { - return transferDay; - } - - public BankAccount getBankAccount() { - return bankAccount; - } - - public TransferInterval getTransferInterval() { - return transferInterval; - } - - public DateTime getLastTransfer() { - return lastTransfer; - } - - public DateTime getUpdatedAt() { - return updatedAt; - } - - public void setTransferEnabled(Boolean transferEnabled) { - this.transferEnabled = transferEnabled; - addUnsavedProperty("transferEnabled"); - } - - public void setTransferDay(Integer transferDay) { - this.transferDay = transferDay; - addUnsavedProperty("transferDay"); - } - - public void setBankAccountId(Integer bankAccountId) { - this.bankAccountId = bankAccountId; - addUnsavedProperty("bankAccountId"); - } - - public void setBankAccount(BankAccount bankAccount) { - this.bankAccount = bankAccount; - addUnsavedProperty("bankAccount"); - } - - public void setTransferInterval(TransferInterval transferInterval) { - this.transferInterval = transferInterval; - addUnsavedProperty("transferInterval"); - } - - public Recipient save() throws PagarMeException { - final Recipient saved = super.save(getClass()); - copy(saved); - - return saved; - } - - public Collection findAll() throws PagarMeException { - return find(100, 0); - } - - public Collection find(int totalPerPage, int page) throws PagarMeException { - return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { - }.getType()); - } - - public Balance balance() throws PagarMeException { - final Balance balance = new Balance(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, - String.format("/%s/%s/%s", getClassName(), getId(), balance.getClassName())); - - return JsonUtils.getAsObject((JsonObject) request.execute(), Balance.class); - } - - public Recipient refresh() throws PagarMeException { - final Recipient other = JsonUtils.getAsObject(refreshModel(), Recipient.class); - copy(other); - flush(); - return other; - } - - /** - * Retornando todas as antecipações - * - * @return {@link Collection} contendo objetos de antecipações. - * @throws PagarMeException - */ - public Collection bulkAnticipations() throws PagarMeException { - validateId(); - - final BulkAnticipation bulkAnticipation = new BulkAnticipation(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), - getId(), bulkAnticipation.getClassName())); - - return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { - }.getType()); - } - - /** - * Criando uma antecipação - * - * @param bulkAnticipation - * @return - * @throws PagarMeException - */ - public BulkAnticipation bulkAnticipations(final BulkAnticipation bulkAnticipation) throws PagarMeException { - validateId(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, - String.format("/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName())); - request.setParameters(JsonUtils.objectToMap(bulkAnticipation)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); - } - - /** - * Confirma a antecipação criada, assim seu status passará para pending, ou seja, está criada com sucesso e - * aguardando aprovação do Pagar.me. - * - * @param bulkAnticipationId - * @return - * @throws PagarMeException - */ - public BulkAnticipation bulkAnticipationsConfirm(final String bulkAnticipationId) throws PagarMeException { - validateId(); - - final BulkAnticipation bulkAnticipation = new BulkAnticipation(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, - String.format("/%s/%s/%s/%s/confirm", getClassName(), getId(), bulkAnticipation.getClassName(), - bulkAnticipationId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); - } - - /** - * Cancela uma antecipação com status pending. Enquanto a antecipação foi criada e o Pagar.me ainda não a confirmou, - * você pode cancelar a antecipação a qualquer momento. - * - * @param bulkAnticipationId - * @return - * @throws PagarMeException - */ - public BulkAnticipation bulkAnticipationsCancel(final String bulkAnticipationId) throws PagarMeException { - validateId(); - - final BulkAnticipation bulkAnticipation = new BulkAnticipation(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, - String.format("/%s/%s/%s/%s/cancel", getClassName(), getId(), - bulkAnticipation.getClassName(), bulkAnticipationId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); - } - - /** - * Enquanto você está construindo uma antecipação (status building), você pode cancelar o processo deletando a - * criação daquela antecipação. Lembrando que caso você não a destrua no status building, após 5 minutos ela é - * automaticamente destruída. - * - * @param bulkAnticipationId - * @return - * @throws PagarMeException - */ - public BulkAnticipation bulkAnticipationsDelete(final String bulkAnticipationId) throws PagarMeException { - validateId(); - - final BulkAnticipation bulkAnticipation = new BulkAnticipation(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, - String.format("/%s/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName(), - bulkAnticipationId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); - } - - public BulkAnticipation.Limits bulkAnticipationsLimits() throws PagarMeException { - final BulkAnticipation bulkAnticipation = new BulkAnticipation(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, - String.format("/%s/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName(), - BulkAnticipation.Limits.class.getSimpleName().toLowerCase())); - - return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.Limits.class); - } - - private void copy(Recipient other) { - setId(other.getId()); - this.automaticAnticipationEnabled = other.automaticAnticipationEnabled; - this.transferEnabled = other.transferEnabled; - this.transferDay = other.transferDay; - this.anticipatableVolumePercentage = other.anticipatableVolumePercentage; - this.lastTransfer = other.lastTransfer; - this.transferInterval = other.transferInterval; - this.updatedAt = other.updatedAt; - this.bankAccount = other.bankAccount; - } - - public enum TransferInterval { - @SerializedName("daily") - DAILY, - - @SerializedName("weekly") - WEEKLY, - - @SerializedName("monthly") - MONTHLY - } + public Integer getAnticipatableVolumePercentage() { + return anticipatableVolumePercentage; + } + + public Integer getTransferDay() { + return transferDay; + } + + public BankAccount getBankAccount() { + return bankAccount; + } + + public TransferInterval getTransferInterval() { + return transferInterval; + } + + public DateTime getLastTransfer() { + return lastTransfer; + } + + public DateTime getUpdatedAt() { + return updatedAt; + } + + public void setTransferEnabled(Boolean transferEnabled) { + this.transferEnabled = transferEnabled; + addUnsavedProperty("transferEnabled"); + } + + public void setTransferDay(Integer transferDay) { + this.transferDay = transferDay; + addUnsavedProperty("transferDay"); + } + + public void setBankAccountId(Integer bankAccountId) { + this.bankAccountId = bankAccountId; + addUnsavedProperty("bankAccountId"); + } + + public void setBankAccount(BankAccount bankAccount) { + this.bankAccount = bankAccount; + addUnsavedProperty("bankAccount"); + } + + public void setTransferInterval(TransferInterval transferInterval) { + this.transferInterval = transferInterval; + addUnsavedProperty("transferInterval"); + } + + public Recipient save() throws PagarMeException { + final Recipient saved = super.save(getClass()); + copy(saved); + + return saved; + } + + public Collection findAll() throws PagarMeException { + return find(100, 0); + } + + public Collection find(int totalPerPage, int page) throws PagarMeException { + return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { + }.getType()); + } + + public Balance balance() throws PagarMeException { + final Balance balance = new Balance(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, + String.format("/%s/%s/%s", getClassName(), getId(), balance.getClassName())); + + return JsonUtils.getAsObject((JsonObject) request.execute(), Balance.class); + } + + public Recipient refresh() throws PagarMeException { + final Recipient other = JsonUtils.getAsObject(refreshModel(), Recipient.class); + copy(other); + flush(); + return other; + } + + /** + * Retornando todas as antecipações + * + * @return {@link Collection} contendo objetos de antecipações. + * @throws PagarMeException + */ + public Collection bulkAnticipations() throws PagarMeException { + validateId(); + + final BulkAnticipation bulkAnticipation = new BulkAnticipation(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), + getId(), bulkAnticipation.getClassName())); + + return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { + }.getType()); + } + + /** + * Criando uma antecipação + * + * @param bulkAnticipation + * @return + * @throws PagarMeException + */ + public BulkAnticipation bulkAnticipations(final BulkAnticipation bulkAnticipation) throws PagarMeException { + validateId(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, + String.format("/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName())); + request.setParameters(JsonUtils.objectToMap(bulkAnticipation)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); + } + + /** + * Confirma a antecipação criada, assim seu status passará para pending, ou seja, está criada com sucesso e + * aguardando aprovação do Pagar.me. + * + * @param bulkAnticipationId + * @return + * @throws PagarMeException + */ + public BulkAnticipation bulkAnticipationsConfirm(final String bulkAnticipationId) throws PagarMeException { + validateId(); + + final BulkAnticipation bulkAnticipation = new BulkAnticipation(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, + String.format("/%s/%s/%s/%s/confirm", getClassName(), getId(), bulkAnticipation.getClassName(), + bulkAnticipationId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); + } + + /** + * Cancela uma antecipação com status pending. Enquanto a antecipação foi criada e o Pagar.me ainda não a confirmou, + * você pode cancelar a antecipação a qualquer momento. + * + * @param bulkAnticipationId + * @return + * @throws PagarMeException + */ + public BulkAnticipation bulkAnticipationsCancel(final String bulkAnticipationId) throws PagarMeException { + validateId(); + + final BulkAnticipation bulkAnticipation = new BulkAnticipation(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, + String.format("/%s/%s/%s/%s/cancel", getClassName(), getId(), + bulkAnticipation.getClassName(), bulkAnticipationId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); + } + + /** + * Enquanto você está construindo uma antecipação (status building), você pode cancelar o processo deletando a + * criação daquela antecipação. Lembrando que caso você não a destrua no status building, após 5 minutos ela é + * automaticamente destruída. + * + * @param bulkAnticipationId + * @return + * @throws PagarMeException + */ + public BulkAnticipation bulkAnticipationsDelete(final String bulkAnticipationId) throws PagarMeException { + validateId(); + + final BulkAnticipation bulkAnticipation = new BulkAnticipation(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, + String.format("/%s/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName(), + bulkAnticipationId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.class); + } + + public BulkAnticipation.Limits bulkAnticipationsLimits() throws PagarMeException { + final BulkAnticipation bulkAnticipation = new BulkAnticipation(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, + String.format("/%s/%s/%s/%s", getClassName(), getId(), bulkAnticipation.getClassName(), + BulkAnticipation.Limits.class.getSimpleName().toLowerCase())); + + return JsonUtils.getAsObject((JsonObject) request.execute(), BulkAnticipation.Limits.class); + } + + private void copy(Recipient other) { + setId(other.getId()); + this.automaticAnticipationEnabled = other.automaticAnticipationEnabled; + this.transferEnabled = other.transferEnabled; + this.transferDay = other.transferDay; + this.anticipatableVolumePercentage = other.anticipatableVolumePercentage; + this.lastTransfer = other.lastTransfer; + this.transferInterval = other.transferInterval; + this.updatedAt = other.updatedAt; + this.bankAccount = other.bankAccount; + } + + public enum TransferInterval { + @SerializedName("daily") + DAILY, + + @SerializedName("weekly") + WEEKLY, + + @SerializedName("monthly") + MONTHLY + } } diff --git a/src/main/java/me/pagar/RestClient.java b/src/main/java/me/pagar/RestClient.java index 4083b9e..22f713c 100644 --- a/src/main/java/me/pagar/RestClient.java +++ b/src/main/java/me/pagar/RestClient.java @@ -4,262 +4,227 @@ import com.google.gson.JsonElement; import com.google.gson.JsonSyntaxException; import me.pagar.util.JsonUtils; +import me.pagar.util.PagarMeSSLSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.UriBuilder; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; import java.util.*; public class RestClient { - private final static String API_KEY = "api_key"; + private final static String API_KEY = "api_key"; - public final static String AMOUNT = "amount"; + public final static String AMOUNT = "amount"; - private final static Logger LOGGER = LoggerFactory.getLogger(RestClient.class); + private final static Logger LOGGER = LoggerFactory.getLogger(RestClient.class); - private HttpsURLConnection httpClient; + private HttpsURLConnection httpClient; - private String method; + private String method; - private String url; + private String url; - private Map parameters; + private Map parameters; - private InputStream is; + private InputStream is; - private void setupSecureConnection(final HttpsURLConnection httpClient) throws KeyStoreException, - IOException, CertificateException, NoSuchAlgorithmException, KeyManagementException { - final URL certFile = Thread.currentThread().getContextClassLoader() - .getResource("pagarme.crt"); + private String getUserAgent() { + final Package pkg = getClass().getPackage(); - if (null == certFile) { - return; - } + String title = pkg.getImplementationTitle(); + if (Strings.isNullOrEmpty(title)) { + title = "pagarme-java"; + } - final Certificate cert = CertificateFactory.getInstance("X.509") - .generateCertificate(certFile.openStream()); + String version = pkg.getImplementationVersion(); + if (Strings.isNullOrEmpty(version)) { + version = "DEV"; + } - final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, null); - keyStore.setCertificateEntry("pagarme", cert); + final String userAgent = String.format("%s/%s (%s; %s/%s)", title, version, + System.getProperty("java.vm.vendor", "Generic"), + System.getProperty("java.vm.name", "Java"), + System.getProperty("java.version", "1.0")); - final TrustManagerFactory tmf = TrustManagerFactory.getInstance("X.509"); - tmf.init(keyStore); + return userAgent; + } - final SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(null, tmf.getTrustManagers(), null); + public RestClient(final String method, final String url) throws PagarMeException { + this(method, url, null, null); + } - httpClient.setSSLSocketFactory(ctx.getSocketFactory()); - } + public RestClient(final String method, final String url, Map parameters) throws PagarMeException { + this(method, url, parameters, null); + } - private String getUserAgent() { - final Package pkg = getClass().getPackage(); + @SuppressWarnings("unchecked") + public RestClient(final String method, final String url, Map parameters, + Map headers) throws PagarMeException { + this.method = method.toUpperCase(); + this.url = url; + this.parameters = parameters; - String title = pkg.getImplementationTitle(); - if (Strings.isNullOrEmpty(title)) { - title = "pagarme-java"; - } + if (null == headers) { + headers = new HashMap(); + } - String version = pkg.getImplementationVersion(); - if (Strings.isNullOrEmpty(version)) { - version = "DEV"; - } + if (null == this.parameters) { + this.parameters = new HashMap(); + } - final String userAgent = String.format("%s/%s (%s; %s/%s)", title, version, - System.getProperty("java.vm.vendor", "Generic"), - System.getProperty("java.vm.name", "Java"), - System.getProperty("java.version", "1.0")); + headers.put("User-Agent", getUserAgent()); + headers.put("Accept", "application/json"); - return userAgent; - } + if (Strings.isNullOrEmpty(url)) { + throw new PagarMeException("You must set the URL to make a request."); + } - public RestClient(final String method, final String url) throws PagarMeException { - this(method, url, null, null); - } + if (!Strings.isNullOrEmpty(method)) { - public RestClient(final String method, final String url, Map parameters) throws PagarMeException { - this(method, url, parameters, null); - } + try { + final UriBuilder builder = UriBuilder.fromPath(this.url); + builder.queryParam(API_KEY, PagarMe.getApiKey()); - @SuppressWarnings("unchecked") - public RestClient(final String method, final String url, Map parameters, - Map headers) throws PagarMeException { - this.method = method.toUpperCase(); - this.url = url; - this.parameters = parameters; + if (this.parameters.containsKey(AMOUNT) && this.parameters.size() == 1) { + builder.queryParam(AMOUNT, this.parameters.remove(AMOUNT)); + } - if (null == headers) { - headers = new HashMap(); - } + if (method.equalsIgnoreCase(HttpMethod.GET)) { - if (null == this.parameters) { - this.parameters = new HashMap(); - } + for (Map.Entry entry : this.parameters.entrySet()) { + builder.queryParam(entry.getKey(), entry.getValue()); + } - headers.put("User-Agent", getUserAgent()); - headers.put("Accept", "application/json"); + } - if (Strings.isNullOrEmpty(url)) { - throw new PagarMeException("You must set the URL to make a request."); - } + httpClient = (HttpsURLConnection) builder + .build(this) + .toURL() + .openConnection(); + httpClient.setRequestMethod(this.method); + httpClient.setDoInput(true); + httpClient.setDoOutput(false); + httpClient.setSSLSocketFactory(new PagarMeSSLSocketFactory()); - if (!Strings.isNullOrEmpty(method)) { + if (headers.size() > 0) { - try { - final UriBuilder builder = UriBuilder.fromPath(this.url); - builder.queryParam(API_KEY, PagarMe.getApiKey()); + for (Map.Entry entry : headers.entrySet()) { + httpClient.addRequestProperty(entry.getKey(), entry.getValue()); + } - if (this.parameters.containsKey(AMOUNT) && this.parameters.size() == 1) { - builder.queryParam(AMOUNT, this.parameters.remove(AMOUNT)); - } + } - if (method.equalsIgnoreCase(HttpMethod.GET)) { + } catch (Exception e) { + throw PagarMeException.buildWithError(e); + } - for (Map.Entry entry : this.parameters.entrySet()) { - builder.queryParam(entry.getKey(), entry.getValue()); - } + } - } + } - httpClient = (HttpsURLConnection) builder - .build(this) - .toURL() - .openConnection(); - httpClient.setRequestMethod(this.method); - httpClient.setDoInput(true); - httpClient.setDoOutput(false); + public PagarMeResponse execute() throws PagarMeException { + final StringBuilder builder = new StringBuilder(); + int responseCode = -1; - setupSecureConnection(httpClient); + try { + LOGGER.trace("{} {}", httpClient.getRequestMethod(), httpClient.getURL().toString()); - if (headers.size() > 0) { + if (method.equalsIgnoreCase(HttpMethod.POST) || + method.equalsIgnoreCase(HttpMethod.PUT) || + method.equalsIgnoreCase(HttpMethod.DELETE)) { + httpClient.setDoOutput(true); - for (Map.Entry entry : headers.entrySet()) { - httpClient.addRequestProperty(entry.getKey(), entry.getValue()); - } + if (parameters.size() > 1) { + final String payload = JsonUtils.getInterpreter().toJson(parameters); + final byte[] rawPayload = payload.getBytes(); + httpClient.addRequestProperty("Content-Type", "application/json"); - } + traceRequest(payload); - } catch (Exception e) { - throw PagarMeException.buildWithError(e); - } + final OutputStream os = httpClient.getOutputStream(); + os.write(rawPayload); + os.flush(); + } - } + } else { + traceRequest(); + } - } + try { + is = httpClient.getInputStream(); + responseCode = httpClient.getResponseCode(); + } catch (IOException e) { + is = httpClient.getErrorStream(); + responseCode = httpClient.getResponseCode(); + } - public PagarMeResponse execute() throws PagarMeException { - final StringBuilder builder = new StringBuilder(); - int responseCode = -1; + // @see http://web.archive.org/web/20140531042945/https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html + final Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); + final String response = s.hasNext() ? s.next() : ""; - try { - LOGGER.trace("{} {}", httpClient.getRequestMethod(), httpClient.getURL().toString()); + traceResponse(response); - if (method.equalsIgnoreCase(HttpMethod.POST) || - method.equalsIgnoreCase(HttpMethod.PUT) || - method.equalsIgnoreCase(HttpMethod.DELETE)) { - httpClient.setDoOutput(true); + httpClient.disconnect(); - if (parameters.size() > 1) { - final String payload = JsonUtils.getInterpreter().toJson(parameters); - final byte[] rawPayload = payload.getBytes(); - httpClient.addRequestProperty("Content-Type", "application/json"); + return new PagarMeResponse(responseCode, + JsonUtils.getInterpreter().fromJson(response, JsonElement.class)); + } catch (Exception e) { - traceRequest(payload); + if (e instanceof JsonSyntaxException) { + throw new PagarMeException(responseCode, url, method, builder.toString()); + } - final OutputStream os = httpClient.getOutputStream(); - os.write(rawPayload); - os.flush(); - } + throw PagarMeException.buildWithError(e); + } - } else { - traceRequest(); - } + } - try { - is = httpClient.getInputStream(); - responseCode = httpClient.getResponseCode(); - } catch (IOException e) { - is = httpClient.getErrorStream(); - responseCode = httpClient.getResponseCode(); - } + private void traceRequest() { + traceRequest(null); + } - // @see http://web.archive.org/web/20140531042945/https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html - final Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); - final String response = s.hasNext() ? s.next() : ""; + private void traceRequest(String payload) { + final StringBuilder traceLog = new StringBuilder("\nRequest Headers:\n"); - traceResponse(response); + extractHeaders(traceLog, httpClient.getRequestProperties().entrySet().iterator()); - httpClient.disconnect(); + if (!Strings.isNullOrEmpty(payload)) + traceLog.append("Payload:\n ") + .append(payload).append("\n"); + LOGGER.trace(traceLog.toString()); + } - return new PagarMeResponse(responseCode, - JsonUtils.getInterpreter().fromJson(response, JsonElement.class)); - } catch (Exception e) { + private void extractHeaders(StringBuilder traceLog, Iterator>> i) { + while (i.hasNext()) { + final Map.Entry> entry = i.next(); + traceLog.append(" "); - if (e instanceof JsonSyntaxException) { - throw new PagarMeException(responseCode, url, method, builder.toString()); - } + if (!Strings.isNullOrEmpty(entry.getKey())) + traceLog.append(entry.getKey()) + .append(": "); - throw PagarMeException.buildWithError(e); - } + if (entry.getValue().size() == 1) { + traceLog.append(entry.getValue().get(0)).append("\n"); + } else { + traceLog.append(entry.getValue()).append("\n"); + } + } + } - } + private void traceResponse(String body) { + final StringBuilder traceLog = new StringBuilder("\nResponse Headers:\n"); - private void traceRequest() { - traceRequest(null); - } + extractHeaders(traceLog, httpClient.getHeaderFields().entrySet().iterator()); - private void traceRequest(String payload) { - final StringBuilder traceLog = new StringBuilder("\nRequest Headers:\n"); - - extractHeaders(traceLog, httpClient.getRequestProperties().entrySet().iterator()); - - if (!Strings.isNullOrEmpty(payload)) - traceLog.append("Payload:\n ") - .append(payload).append("\n"); - LOGGER.trace(traceLog.toString()); - } - - private void extractHeaders(StringBuilder traceLog, Iterator>> i) { - while (i.hasNext()) { - final Map.Entry> entry = i.next(); - traceLog.append(" "); - - if (!Strings.isNullOrEmpty(entry.getKey())) - traceLog.append(entry.getKey()) - .append(": "); - - if (entry.getValue().size() == 1) { - traceLog.append(entry.getValue().get(0)).append("\n"); - } else { - traceLog.append(entry.getValue()).append("\n"); - } - } - } - - private void traceResponse(String body) { - final StringBuilder traceLog = new StringBuilder("\nResponse Headers:\n"); - - extractHeaders(traceLog, httpClient.getHeaderFields().entrySet().iterator()); - - if (!Strings.isNullOrEmpty(body)) - traceLog.append("Body:\n ") - .append(body).append("\n"); - LOGGER.trace(traceLog.toString()); - } + if (!Strings.isNullOrEmpty(body)) + traceLog.append("Body:\n ") + .append(body).append("\n"); + LOGGER.trace(traceLog.toString()); + } } diff --git a/src/main/java/me/pagar/SplitRule.java b/src/main/java/me/pagar/SplitRule.java index 93ee71a..db7e951 100644 --- a/src/main/java/me/pagar/SplitRule.java +++ b/src/main/java/me/pagar/SplitRule.java @@ -6,77 +6,77 @@ public class SplitRule extends PagarMeModel { - @Expose - private String recipientId; + @Expose + private String recipientId; - @Expose - private Boolean chargeProcessingFee; + @Expose + private Boolean chargeProcessingFee; - @Expose - private Boolean liable; + @Expose + private Boolean liable; - @Expose - private Integer percentage; + @Expose + private Integer percentage; - @Expose - private Integer amount; + @Expose + private Integer amount; - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; - public String getRecipientId() { - return recipientId; - } + public String getRecipientId() { + return recipientId; + } - public Boolean getChargeProcessingFee() { - return chargeProcessingFee; - } + public Boolean getChargeProcessingFee() { + return chargeProcessingFee; + } - public Boolean getLiable() { - return liable; - } + public Boolean getLiable() { + return liable; + } - public Integer getPercentage() { - return percentage; - } + public Integer getPercentage() { + return percentage; + } - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - public DateTime getUpdatedAt() { - return updatedAt; - } + public DateTime getUpdatedAt() { + return updatedAt; + } - public void setRecipientId(String recipientId) { - this.recipientId = recipientId; - } + public void setRecipientId(String recipientId) { + this.recipientId = recipientId; + } - public void setChargeProcessingFee(Boolean chargeProcessingFee) { - this.chargeProcessingFee = chargeProcessingFee; - } + public void setChargeProcessingFee(Boolean chargeProcessingFee) { + this.chargeProcessingFee = chargeProcessingFee; + } - public void setLiable(Boolean liable) { - this.liable = liable; - } + public void setLiable(Boolean liable) { + this.liable = liable; + } - public void setPercentage(Integer percentage) { - this.percentage = percentage; - } + public void setPercentage(Integer percentage) { + this.percentage = percentage; + } - public void setAmount(Integer amount) { - this.amount = amount; - } + public void setAmount(Integer amount) { + this.amount = amount; + } - @Override - public void setId(String id) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setId(String id) { + throw new UnsupportedOperationException("Not allowed."); + } - @Override - public void setClassName(String className) { - throw new UnsupportedOperationException("Not allowed."); - } + @Override + public void setClassName(String className) { + throw new UnsupportedOperationException("Not allowed."); + } } diff --git a/src/main/java/me/pagar/Transaction.java b/src/main/java/me/pagar/Transaction.java index 164ec1b..27c80ee 100644 --- a/src/main/java/me/pagar/Transaction.java +++ b/src/main/java/me/pagar/Transaction.java @@ -22,878 +22,878 @@ */ public class Transaction extends PagarMeModel { - @Expose(deserialize = false) - private Boolean async; - - @Expose(deserialize = false) - private Boolean capture; - - /** - * Caso essa transação tenha sido originada na cobrança de uma assinatura, o id desta será o valor - * dessa propriedade - */ - @Expose(serialize = false) - private Integer subscriptionId; - - /** - * Valor, em centavos, da transação - */ - @Expose - private Integer amount; - - /** - * Número de parcelas/prestações a serem cobradas - */ - @Expose - private Integer installments; - - @Expose(deserialize = false) - private String cardId; - - /** - * Custo da transação para o lojista - */ - @Expose(serialize = false) - private Integer cost; - - /** - * Mensagem de resposta do adquirente referente ao status da transação. - */ - @Expose(serialize = false) - private String acquirerResponseCode; - - /** - * Código de autorização retornado pela bandeira. - */ - @Expose(serialize = false) - private String authorizationCode; - - /** - * Texto que irá aparecer na fatura do cliente depois do nome da loja. - * OBS: Limite de 13 caracteres. - */ - private String softDescriptor; - - /** - * Código que identifica a transação no adquirente. - */ - @Expose(serialize = false) - private String tid; - - /** - * Código que identifica a transação no adquirente. - */ - @Expose(serialize = false) - private String nsu; - - /** - * URL (endpoint) do sistema integrado a Pagar.me que receberá as respostas a cada atualização do - * processamento da transação - */ - @Expose - private String postbackUrl; - - /** - * URL do boleto para impressão - */ - @Expose(serialize = false) - private String boletoUrl; - - /** - * Código de barras do boleto gerado na transação - */ - @Expose(serialize = false) - private String boletoBarcode; - - /** - * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. - */ - @Expose(serialize = false) - private String referer; - - /** - * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. - */ - @Expose(serialize = false) - private String ip; - - @Expose(deserialize = false) - private String cardHash; - - /** - * Adquirente responsável pelo processamento da transação. - */ - @Expose(serialize = false) - private AcquirerName acquirerName; - - /** - * Método de pagamento possíveis: credit_card e boleto - */ - @Expose - private PaymentMethod paymentMethod; - - /** - * Para cada atualização no processamento da transação, esta propriedade será alterada, e o objeto - * transaction retornado como resposta através da sua URL de postback ou após o término do - * processamento da ação atual. - */ - @Expose(serialize = false) - private Status status; - - /** - * Motivo/agente responsável pela validação ou anulação da transação. - */ - @Expose(serialize = false) - private StatusReason statusReason; - - /** - * Data de expiração do boleto (em ISODate) - */ - @Expose(deserialize = false) - private DateTime boletoExpirationDate; - - /** - * Data de atualização da transação no formato ISODate - */ - @Expose(serialize = false) - @SerializedName("date_updated") - private DateTime updatedAt; - - /** - * Objeto com dados do telefone do cliente - */ - @Expose(serialize = false) - private Phone phone; - - /** - * Objeto com dados do endereço do cliente - */ - @Expose(serialize = false) - private Address address; - - /** - * Objeto com dados do cliente - */ - @Expose - private Customer customer; - - /** - * Objeto com dados do cartão do cliente - */ - @Expose(serialize = false) - private Card card; - - /** - * Objeto com dados adicionais do cliente/produto/serviço vendido - */ - @Expose - private Map metadata; - - @Expose(serialize = false) - private Event event; - - @Expose(serialize = false) - private Status oldStatus; - - @Expose(serialize = false) - private Status currentStatus; - - @Expose(serialize = false) - private Status desiredStatus; - - @Expose(deserialize = false) - private Collection splitRules; - - public Transaction() { - super(); - this.splitRules = new ArrayList(); - } - - /** - * OBS: Apenas para transações de cartão de crédito você deve passar ou o - * card_hash ou o card_id. - * - * @param amount Valor a ser cobrado. Deve ser passado em centavos. - * @param cardHash Informações do cartão do cliente criptografadas no navegador. - * @param cardId Ao realizar uma transação, retornamos o card_id do cartão para que nas próximas - * transações desse cartão possa ser utilizado esse identificador ao invés do card_hash - * @param customer Dados do cliente a ser cadastrado - */ - public Transaction(final Integer amount, final String cardHash, final String cardId, final Customer customer) { - this(); - this.amount = amount; - this.cardHash = cardHash; - this.cardId = cardId; - this.customer = customer; - } - - /** - * @return {@link #subscriptionId} - */ - public Integer getSubscriptionId() { - return subscriptionId; - } - - /** - * @return {@link #amount} - */ - public Integer getAmount() { - return amount; - } - - /** - * @return {@link #installments} - */ - public Integer getInstallments() { - return installments; - } - - /** - * @return {@link #cost} - */ - public Integer getCost() { - return cost; - } - - /** - * @return {@link #acquirerResponseCode} - */ - public String getAcquirerResponseCode() { - return acquirerResponseCode; - } - - /** - * @return {@link #authorizationCode} - */ - public String getAuthorizationCode() { - return authorizationCode; - } - - /** - * @return {@link #softDescriptor} - */ - public String getSoftDescriptor() { - return softDescriptor; - } - - /** - * @return {@link #tid} - */ - public String getTid() { - return tid; - } - - /** - * @return {@link #nsu} - */ - public String getNsu() { - return nsu; - } - - /** - * @return {@link Transaction#postbackUrl} - */ - public String getPostbackUrl() { - return postbackUrl; - } - - public String getBoletoUrl() { - return boletoUrl; - } - - /** - * @return {@link #boletoBarcode} - */ - public String getBoletoBarcode() { - return boletoBarcode; - } - - /** - * @return {@link #referer} - */ - public String getReferer() { - return referer; - } - - /** - * @return {@link #ip} - */ - public String getIp() { - return ip; - } - - /** - * @return {@link #acquirerName} - */ - public AcquirerName getAcquirerName() { - return acquirerName; - } - - /** - * @return {@link #paymentMethod} - */ - public PaymentMethod getPaymentMethod() { - return paymentMethod; - } - - /** - * @return {@link #status} - */ - public Status getStatus() { - return status; - } - - /** - * @return {@link #statusReason} - */ - public StatusReason getStatusReason() { - return statusReason; - } - - /** - * @return {@link #updatedAt} - */ - public DateTime getUpdatedAt() { - return updatedAt; - } - - /** - * @return {@link #metadata} - */ - public Map getMetadata() { - return metadata; - } - - /** - * @return {@link #card} - */ - public Card getCard() { - return card; - } - - /** - * @return {@link #customer} - */ - public Customer getCustomer() { - return customer; - } - - /** - * @return {@link #event} - */ - public Event getEvent() { - return event; - } - - /** - * @return {@link #oldStatus} - */ - public Status getOldStatus() { - return oldStatus; - } - - /** - * @return {@link #currentStatus} - */ - public Status getCurrentStatus() { - return currentStatus; - } - - /** - * @return {@link #desiredStatus} - */ - public Status getDesiredStatus() { - return desiredStatus; - } - - public void setAsync(final Boolean async) { - this.async = async; - addUnsavedProperty("async"); - } - - public void setCapture(final Boolean capture) { - this.capture = capture; - addUnsavedProperty("capture"); - } - - public void setAmount(final Integer amount) { - this.amount = amount; - addUnsavedProperty("amount"); - } - - public void setInstallments(final Integer installments) { - this.installments = installments; - addUnsavedProperty("installments"); - } - - public void setSoftDescriptor(final String softDescriptor) { - this.softDescriptor = softDescriptor; - addUnsavedProperty("softDescriptor"); - } - - public void setPostbackUrl(final String postbackUrl) { - this.postbackUrl = postbackUrl; - addUnsavedProperty("postbackUrl"); - } - - public void setCardHash(final String cardHash) { - this.cardHash = cardHash; - addUnsavedProperty("cardHash"); - } - - public void setPaymentMethod(final PaymentMethod paymentMethod) { - this.paymentMethod = paymentMethod; - addUnsavedProperty("paymentMethod"); - } - - public void setCardId(final String cardId) { - this.cardId = cardId; - addUnsavedProperty("cardId"); - } - - public void setCustomer(final Customer customer) { - this.customer = customer; - addUnsavedProperty("customer"); - } - - public void setBoletoExpirationDate(final DateTime boletoExpirationDate) { - this.boletoExpirationDate = boletoExpirationDate; - addUnsavedProperty("boletoExpirationDate"); - } - - public void setMetadata(final Map metadata) { - this.metadata = metadata; - addUnsavedProperty("metadata"); - } - - public void setSplitRules(final Collection splitRules) { - this.splitRules = splitRules; - addUnsavedProperty("splitRules"); - } - - public Transaction save() throws PagarMeException { - final Transaction saved = super.save(getClass()); - copy(saved); - - return saved; - } - - /** - * @see #list(int, int) - */ - public Collection list() throws PagarMeException { - return list(100, 0); - } - - /** - * @param totalPerPage Retorna n objetos de transação - * @param page Útil para implementação de uma paginação de resultados - * @return Uma {@link Collection} contendo objetos de transações, ordenadas a partir da transação realizada mais - * recentemente. - * @throws PagarMeException - */ - public Collection list(int totalPerPage, int page) throws PagarMeException { - return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { - }.getType()); - } - - /** - * Caso você queira/precise criar o card_hash manualmente, essa rota deverá ser utilizada para obtenção de uma chave - * pública de encriptação dos dados do cartão de seu cliente. - * - * @return Um {@link CardHashKey} - * @throws PagarMeException - */ - public CardHashKey cardHashKey() throws PagarMeException { - final String cardHashKeyEndpoint = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, - CardHashKey.class.getSimpleName()); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), - cardHashKeyEndpoint)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), CardHashKey.class); - } - - /** - * Retorna uma {@link AntifraudAnalysis} específica realizada em uma transação. - * - * @param antifraudAnalysisId ID da {@link AntifraudAnalysis} feita - * @return Uma {@link AntifraudAnalysis} - * @throws PagarMeException - */ - public AntifraudAnalysis antifraudAnalysis(final Integer antifraudAnalysisId) throws PagarMeException { - validateId(); - - final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), - getId(), antifraudAnalysis.getClassName(), antifraudAnalysisId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), AntifraudAnalysis.class); - } - - /** - * Retorna todas as {@link AntifraudAnalysis} realizadas em uma transação. - * - * @return Lista de {@link AntifraudAnalysis} - * @throws PagarMeException - */ - public Collection antifraudAnalysises() throws PagarMeException { - validateId(); - - final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), - getId(), antifraudAnalysis.getClassName())); - - return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { - }.getType()); - } - - /** - * Retorna um objeto {@link Payable} informando os dados de um pagamento referente a uma determinada transação. - * - * @param payableId ID do {@link Payable} - * @return Um {@link Payable} - * @throws PagarMeException - */ - public Payable payables(final Integer payableId) throws PagarMeException { - validateId(); - - final Payable splitRule = new Payable(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), - getId(), splitRule.getClassName(), payableId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), Payable.class); - } - - /** - * Retorna um array com objetos {@link Payable} informando os dados dos pagamentos referentes a uma transação. - * - * @return Lista de {@link Payable} - * @throws PagarMeException - */ - public Collection payables() throws PagarMeException { - validateId(); - - final Payable payable = new Payable(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), - getId(), payable.getClassName())); - - return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { - }.getType()); - } - - /** - * Retorna um {@link Postback} específico relacionado a transação. - * - * @param postbackId ID do {@link Postback} - * @return Um {@link Postback} - * @throws PagarMeException - */ - public Postback postbacks(final String postbackId) throws PagarMeException { - validateId(); - - final Postback postback = new Postback(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), - getId(), postback.getClassName(), postbackId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), Postback.class); - } - - /** - * Com essa rota você pode reenviar qualquer {@link Postback} que já foi enviado de uma transação. Lembrando que - * caso o envio de um {@link Postback} falhe ou seu servidor não o receba, nós o retentamos diversas vezes (com um - * total de 31 vezes). - * - * @param postbackId ID do {@link Postback} - * @return Reenviando um {@link Postback} - * @throws PagarMeException - */ - public Postback postbackRedeliver(final String postbackId) throws PagarMeException { - validateId(); - - final Postback postback = new Postback(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/%s/%s/redeliver", - getClassName(), getId(), postback.getClassName(), postbackId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), Postback.class); - } - - /** - * Retorna todos os {@link Postback} enviados relacionados a transação. - * - * @return Todos os {@link Postback}s - * @throws PagarMeException - */ - public Collection postbacks() throws PagarMeException { - validateId(); - - final Postback postback = new Postback(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), - getId(), postback.getClassName())); - - return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { - }.getType()); - } - - /** - * Retorna os dados das {@link SplitRule} do valor transacionado. - * - * @param splitRuleId O ID da Regra de Split - * @return Retornando uma {@link SplitRule} específica - * @throws PagarMeException - */ - public SplitRule splitRules(final String splitRuleId) throws PagarMeException { - validateId(); - - final SplitRule splitRule = new SplitRule(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), - getId(), splitRule.getClassName(), splitRuleId)); - - return JsonUtils.getAsObject((JsonObject) request.execute(), SplitRule.class); - } - - - /** - * Retorna os dados de uma {@link SplitRule} de uma determinada transação. - * - * @return Lista de {@link SplitRule} para a transação - * @throws PagarMeException - */ - public Collection splitRules() throws PagarMeException { - validateId(); - - final SplitRule splitRule = new SplitRule(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), - getId(), splitRule.getClassName())); - - return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { - }.getType()); - } - - /** - * Essa rota é utilizada quando se deseja estornar uma transação, realizada por uma cobrança via cartão de crédito - * ou boleto bancário. - *

- * Em caso de estorno de uma transação realizada com cartão de crédito, apenas o id da transação é - * necessário para efetivação do estorno. - *

- * Caso a compra tenha sido feita por boleto bancário, você precisará passar os dados da conta bancária que irá - * receber o valor estornado, ou o id desta conta, que pode ser gerada com o modelo {@link BankAccount}. - * - * @throws PagarMeException - */ - public Transaction refund() throws PagarMeException { - validateId(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, - String.format("/%s/%s/refund", getClassName(), getId())); - - final Transaction other = JsonUtils.getAsObject((JsonObject) request.execute(), Transaction.class); - copy(other); - flush(); - - return other; - } - - /** - * Você pode capturar o valor de uma transação após a autorização desta, no prazo máximo de 5 dias após a autorização. - * - * @param amount - * @return - * @throws PagarMeException - */ - public Transaction capture(final Integer amount) throws PagarMeException { - validateId(); - - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, - String.format("/%s/%s/capture", getClassName(), getId())); - request.getParameters().put("amount", amount); - - final Transaction other = JsonUtils.getAsObject((JsonObject) request.execute(), Transaction.class); - copy(other); - flush(); - - return other; - } - - /** - * Atualiza a instância do objeto com os dados mais recentes do backend. - * - * @return Instância atualizada do Objeto. - */ - public Transaction refresh() throws PagarMeException { - final Transaction other = JsonUtils.getAsObject(refreshModel(), Transaction.class); - copy(other); - flush(); - return other; - } - - private void copy(Transaction other) { - setId(other.getId()); - this.status = other.status; - this.statusReason = other.statusReason; - this.acquirerResponseCode = other.acquirerResponseCode; - this.acquirerName = other.acquirerName; - this.authorizationCode = other.authorizationCode; - this.softDescriptor = other.softDescriptor; - this.tid = other.tid; - this.nsu = other.nsu; - this.updatedAt = other.updatedAt; - this.amount = other.amount; - this.installments = other.installments; - this.cost = other.cost; - this.postbackUrl = other.postbackUrl; - this.paymentMethod = other.paymentMethod; - this.boletoUrl = other.boletoUrl; - this.boletoBarcode = other.boletoBarcode; - this.boletoExpirationDate = other.boletoExpirationDate; - this.referer = other.referer; - this.ip = other.ip; - this.subscriptionId = other.subscriptionId; - this.phone = other.phone; - this.address = other.address; - this.customer = other.customer; - this.card = other.card; - this.metadata = other.metadata; - } - - /** - * Adquirente responsável pelo processamento da transação. - */ - public enum AcquirerName { - - /** - * em ambiente de testes - */ - @SerializedName("development") - DEVELOPMENT, - - /** - * adquirente Pagar.me - */ - @SerializedName("pagarme") - PAGARME, - - @SerializedName("stone") - STONE, - - @SerializedName("cielo") - CIELO, - - @SerializedName("rede") - REDE, - - @SerializedName("mundipagg") - MUNDIPAGG - - } - - public enum Event { - - @SerializedName("transaction_status_changed") - TRANSACTION_STATUS_CHANGED - - } - - /** - * Método de pagamento - */ - public enum PaymentMethod { - - @SerializedName("credit_card") - CREDIT_CARD, - - @SerializedName("boleto") - BOLETO - - } - - /** - * Quando uma transação é criada, ela inicialmente é retornada com o status {@link #PROCESSING}. - */ - public enum Status { - - /** - * Transação sendo processada. - */ - @SerializedName("processing") - PROCESSING, - - /** - * Transação autorizada. Cliente possui saldo na conta e este valor foi reservado para futura captura, que deve - * acontecer em no máximo 5 dias. Caso a transação não seja capturada, a autorização é cancelada - * automaticamente. - */ - @SerializedName("authorized") - AUTHORIZED, - - /** - * Transação paga (autorizada e capturada). - */ - @SerializedName("paid") - PAID, - - /** - * Transação estornada. - */ - @SerializedName("refunded") - REFUNDED, - - /** - * Transação aguardando pagamento (status para transações criadas com boleto bancário). - */ - @SerializedName("waiting_payment") - WAITING_PAYMENT, - - /** - * Transação paga com boleto aguardando para ser estornada. - */ - @SerializedName("pending_refund") - PENDING_REFUND, - - /** - * Transação não autorizada. - */ - @SerializedName("refused") - REFUSED, + @Expose(deserialize = false) + private Boolean async; + + @Expose(deserialize = false) + private Boolean capture; + + /** + * Caso essa transação tenha sido originada na cobrança de uma assinatura, o id desta será o valor + * dessa propriedade + */ + @Expose(serialize = false) + private Integer subscriptionId; + + /** + * Valor, em centavos, da transação + */ + @Expose + private Integer amount; + + /** + * Número de parcelas/prestações a serem cobradas + */ + @Expose + private Integer installments; + + @Expose(deserialize = false) + private String cardId; + + /** + * Custo da transação para o lojista + */ + @Expose(serialize = false) + private Integer cost; + + /** + * Mensagem de resposta do adquirente referente ao status da transação. + */ + @Expose(serialize = false) + private String acquirerResponseCode; + + /** + * Código de autorização retornado pela bandeira. + */ + @Expose(serialize = false) + private String authorizationCode; + + /** + * Texto que irá aparecer na fatura do cliente depois do nome da loja. + * OBS: Limite de 13 caracteres. + */ + private String softDescriptor; + + /** + * Código que identifica a transação no adquirente. + */ + @Expose(serialize = false) + private String tid; + + /** + * Código que identifica a transação no adquirente. + */ + @Expose(serialize = false) + private String nsu; + + /** + * URL (endpoint) do sistema integrado a Pagar.me que receberá as respostas a cada atualização do + * processamento da transação + */ + @Expose + private String postbackUrl; + + /** + * URL do boleto para impressão + */ + @Expose(serialize = false) + private String boletoUrl; + + /** + * Código de barras do boleto gerado na transação + */ + @Expose(serialize = false) + private String boletoBarcode; + + /** + * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. + */ + @Expose(serialize = false) + private String referer; + + /** + * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. + */ + @Expose(serialize = false) + private String ip; + + @Expose(deserialize = false) + private String cardHash; + + /** + * Adquirente responsável pelo processamento da transação. + */ + @Expose(serialize = false) + private AcquirerName acquirerName; + + /** + * Método de pagamento possíveis: credit_card e boleto + */ + @Expose + private PaymentMethod paymentMethod; + + /** + * Para cada atualização no processamento da transação, esta propriedade será alterada, e o objeto + * transaction retornado como resposta através da sua URL de postback ou após o término do + * processamento da ação atual. + */ + @Expose(serialize = false) + private Status status; + + /** + * Motivo/agente responsável pela validação ou anulação da transação. + */ + @Expose(serialize = false) + private StatusReason statusReason; + + /** + * Data de expiração do boleto (em ISODate) + */ + @Expose(deserialize = false) + private DateTime boletoExpirationDate; + + /** + * Data de atualização da transação no formato ISODate + */ + @Expose(serialize = false) + @SerializedName("date_updated") + private DateTime updatedAt; + + /** + * Objeto com dados do telefone do cliente + */ + @Expose(serialize = false) + private Phone phone; + + /** + * Objeto com dados do endereço do cliente + */ + @Expose(serialize = false) + private Address address; + + /** + * Objeto com dados do cliente + */ + @Expose + private Customer customer; + + /** + * Objeto com dados do cartão do cliente + */ + @Expose(serialize = false) + private Card card; + + /** + * Objeto com dados adicionais do cliente/produto/serviço vendido + */ + @Expose + private Map metadata; + + @Expose(serialize = false) + private Event event; + + @Expose(serialize = false) + private Status oldStatus; + + @Expose(serialize = false) + private Status currentStatus; + + @Expose(serialize = false) + private Status desiredStatus; + + @Expose(deserialize = false) + private Collection splitRules; + + public Transaction() { + super(); + this.splitRules = new ArrayList(); + } + + /** + * OBS: Apenas para transações de cartão de crédito você deve passar ou o + * card_hash ou o card_id. + * + * @param amount Valor a ser cobrado. Deve ser passado em centavos. + * @param cardHash Informações do cartão do cliente criptografadas no navegador. + * @param cardId Ao realizar uma transação, retornamos o card_id do cartão para que nas próximas + * transações desse cartão possa ser utilizado esse identificador ao invés do card_hash + * @param customer Dados do cliente a ser cadastrado + */ + public Transaction(final Integer amount, final String cardHash, final String cardId, final Customer customer) { + this(); + this.amount = amount; + this.cardHash = cardHash; + this.cardId = cardId; + this.customer = customer; + } + + /** + * @return {@link #subscriptionId} + */ + public Integer getSubscriptionId() { + return subscriptionId; + } + + /** + * @return {@link #amount} + */ + public Integer getAmount() { + return amount; + } + + /** + * @return {@link #installments} + */ + public Integer getInstallments() { + return installments; + } + + /** + * @return {@link #cost} + */ + public Integer getCost() { + return cost; + } + + /** + * @return {@link #acquirerResponseCode} + */ + public String getAcquirerResponseCode() { + return acquirerResponseCode; + } + + /** + * @return {@link #authorizationCode} + */ + public String getAuthorizationCode() { + return authorizationCode; + } + + /** + * @return {@link #softDescriptor} + */ + public String getSoftDescriptor() { + return softDescriptor; + } + + /** + * @return {@link #tid} + */ + public String getTid() { + return tid; + } + + /** + * @return {@link #nsu} + */ + public String getNsu() { + return nsu; + } + + /** + * @return {@link Transaction#postbackUrl} + */ + public String getPostbackUrl() { + return postbackUrl; + } + + public String getBoletoUrl() { + return boletoUrl; + } + + /** + * @return {@link #boletoBarcode} + */ + public String getBoletoBarcode() { + return boletoBarcode; + } + + /** + * @return {@link #referer} + */ + public String getReferer() { + return referer; + } + + /** + * @return {@link #ip} + */ + public String getIp() { + return ip; + } + + /** + * @return {@link #acquirerName} + */ + public AcquirerName getAcquirerName() { + return acquirerName; + } + + /** + * @return {@link #paymentMethod} + */ + public PaymentMethod getPaymentMethod() { + return paymentMethod; + } + + /** + * @return {@link #status} + */ + public Status getStatus() { + return status; + } + + /** + * @return {@link #statusReason} + */ + public StatusReason getStatusReason() { + return statusReason; + } + + /** + * @return {@link #updatedAt} + */ + public DateTime getUpdatedAt() { + return updatedAt; + } + + /** + * @return {@link #metadata} + */ + public Map getMetadata() { + return metadata; + } + + /** + * @return {@link #card} + */ + public Card getCard() { + return card; + } + + /** + * @return {@link #customer} + */ + public Customer getCustomer() { + return customer; + } + + /** + * @return {@link #event} + */ + public Event getEvent() { + return event; + } + + /** + * @return {@link #oldStatus} + */ + public Status getOldStatus() { + return oldStatus; + } + + /** + * @return {@link #currentStatus} + */ + public Status getCurrentStatus() { + return currentStatus; + } + + /** + * @return {@link #desiredStatus} + */ + public Status getDesiredStatus() { + return desiredStatus; + } + + public void setAsync(final Boolean async) { + this.async = async; + addUnsavedProperty("async"); + } + + public void setCapture(final Boolean capture) { + this.capture = capture; + addUnsavedProperty("capture"); + } + + public void setAmount(final Integer amount) { + this.amount = amount; + addUnsavedProperty("amount"); + } + + public void setInstallments(final Integer installments) { + this.installments = installments; + addUnsavedProperty("installments"); + } + + public void setSoftDescriptor(final String softDescriptor) { + this.softDescriptor = softDescriptor; + addUnsavedProperty("softDescriptor"); + } + + public void setPostbackUrl(final String postbackUrl) { + this.postbackUrl = postbackUrl; + addUnsavedProperty("postbackUrl"); + } + + public void setCardHash(final String cardHash) { + this.cardHash = cardHash; + addUnsavedProperty("cardHash"); + } + + public void setPaymentMethod(final PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + addUnsavedProperty("paymentMethod"); + } + + public void setCardId(final String cardId) { + this.cardId = cardId; + addUnsavedProperty("cardId"); + } + + public void setCustomer(final Customer customer) { + this.customer = customer; + addUnsavedProperty("customer"); + } + + public void setBoletoExpirationDate(final DateTime boletoExpirationDate) { + this.boletoExpirationDate = boletoExpirationDate; + addUnsavedProperty("boletoExpirationDate"); + } + + public void setMetadata(final Map metadata) { + this.metadata = metadata; + addUnsavedProperty("metadata"); + } + + public void setSplitRules(final Collection splitRules) { + this.splitRules = splitRules; + addUnsavedProperty("splitRules"); + } + + public Transaction save() throws PagarMeException { + final Transaction saved = super.save(getClass()); + copy(saved); + + return saved; + } + + /** + * @see #list(int, int) + */ + public Collection list() throws PagarMeException { + return list(100, 0); + } + + /** + * @param totalPerPage Retorna n objetos de transação + * @param page Útil para implementação de uma paginação de resultados + * @return Uma {@link Collection} contendo objetos de transações, ordenadas a partir da transação realizada mais + * recentemente. + * @throws PagarMeException + */ + public Collection list(int totalPerPage, int page) throws PagarMeException { + return JsonUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken>() { + }.getType()); + } + + /** + * Caso você queira/precise criar o card_hash manualmente, essa rota deverá ser utilizada para obtenção de uma chave + * pública de encriptação dos dados do cartão de seu cliente. + * + * @return Um {@link CardHashKey} + * @throws PagarMeException + */ + public CardHashKey cardHashKey() throws PagarMeException { + final String cardHashKeyEndpoint = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, + CardHashKey.class.getSimpleName()); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), + cardHashKeyEndpoint)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), CardHashKey.class); + } + + /** + * Retorna uma {@link AntifraudAnalysis} específica realizada em uma transação. + * + * @param antifraudAnalysisId ID da {@link AntifraudAnalysis} feita + * @return Uma {@link AntifraudAnalysis} + * @throws PagarMeException + */ + public AntifraudAnalysis antifraudAnalysis(final Integer antifraudAnalysisId) throws PagarMeException { + validateId(); + + final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), + getId(), antifraudAnalysis.getClassName(), antifraudAnalysisId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), AntifraudAnalysis.class); + } + + /** + * Retorna todas as {@link AntifraudAnalysis} realizadas em uma transação. + * + * @return Lista de {@link AntifraudAnalysis} + * @throws PagarMeException + */ + public Collection antifraudAnalysises() throws PagarMeException { + validateId(); + + final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), + getId(), antifraudAnalysis.getClassName())); + + return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { + }.getType()); + } + + /** + * Retorna um objeto {@link Payable} informando os dados de um pagamento referente a uma determinada transação. + * + * @param payableId ID do {@link Payable} + * @return Um {@link Payable} + * @throws PagarMeException + */ + public Payable payables(final Integer payableId) throws PagarMeException { + validateId(); + + final Payable splitRule = new Payable(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), + getId(), splitRule.getClassName(), payableId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), Payable.class); + } + + /** + * Retorna um array com objetos {@link Payable} informando os dados dos pagamentos referentes a uma transação. + * + * @return Lista de {@link Payable} + * @throws PagarMeException + */ + public Collection payables() throws PagarMeException { + validateId(); + + final Payable payable = new Payable(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), + getId(), payable.getClassName())); + + return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { + }.getType()); + } + + /** + * Retorna um {@link Postback} específico relacionado a transação. + * + * @param postbackId ID do {@link Postback} + * @return Um {@link Postback} + * @throws PagarMeException + */ + public Postback postbacks(final String postbackId) throws PagarMeException { + validateId(); + + final Postback postback = new Postback(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), + getId(), postback.getClassName(), postbackId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), Postback.class); + } + + /** + * Com essa rota você pode reenviar qualquer {@link Postback} que já foi enviado de uma transação. Lembrando que + * caso o envio de um {@link Postback} falhe ou seu servidor não o receba, nós o retentamos diversas vezes (com um + * total de 31 vezes). + * + * @param postbackId ID do {@link Postback} + * @return Reenviando um {@link Postback} + * @throws PagarMeException + */ + public Postback postbackRedeliver(final String postbackId) throws PagarMeException { + validateId(); + + final Postback postback = new Postback(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/%s/%s/redeliver", + getClassName(), getId(), postback.getClassName(), postbackId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), Postback.class); + } + + /** + * Retorna todos os {@link Postback} enviados relacionados a transação. + * + * @return Todos os {@link Postback}s + * @throws PagarMeException + */ + public Collection postbacks() throws PagarMeException { + validateId(); + + final Postback postback = new Postback(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), + getId(), postback.getClassName())); + + return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { + }.getType()); + } + + /** + * Retorna os dados das {@link SplitRule} do valor transacionado. + * + * @param splitRuleId O ID da Regra de Split + * @return Retornando uma {@link SplitRule} específica + * @throws PagarMeException + */ + public SplitRule splitRules(final String splitRuleId) throws PagarMeException { + validateId(); + + final SplitRule splitRule = new SplitRule(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), + getId(), splitRule.getClassName(), splitRuleId)); + + return JsonUtils.getAsObject((JsonObject) request.execute(), SplitRule.class); + } + + + /** + * Retorna os dados de uma {@link SplitRule} de uma determinada transação. + * + * @return Lista de {@link SplitRule} para a transação + * @throws PagarMeException + */ + public Collection splitRules() throws PagarMeException { + validateId(); + + final SplitRule splitRule = new SplitRule(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), + getId(), splitRule.getClassName())); + + return JsonUtils.getAsList((JsonArray) request.execute(), new TypeToken>() { + }.getType()); + } + + /** + * Essa rota é utilizada quando se deseja estornar uma transação, realizada por uma cobrança via cartão de crédito + * ou boleto bancário. + *

+ * Em caso de estorno de uma transação realizada com cartão de crédito, apenas o id da transação é + * necessário para efetivação do estorno. + *

+ * Caso a compra tenha sido feita por boleto bancário, você precisará passar os dados da conta bancária que irá + * receber o valor estornado, ou o id desta conta, que pode ser gerada com o modelo {@link BankAccount}. + * + * @throws PagarMeException + */ + public Transaction refund() throws PagarMeException { + validateId(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, + String.format("/%s/%s/refund", getClassName(), getId())); + + final Transaction other = JsonUtils.getAsObject((JsonObject) request.execute(), Transaction.class); + copy(other); + flush(); + + return other; + } + + /** + * Você pode capturar o valor de uma transação após a autorização desta, no prazo máximo de 5 dias após a autorização. + * + * @param amount + * @return + * @throws PagarMeException + */ + public Transaction capture(final Integer amount) throws PagarMeException { + validateId(); + + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, + String.format("/%s/%s/capture", getClassName(), getId())); + request.getParameters().put("amount", amount); + + final Transaction other = JsonUtils.getAsObject((JsonObject) request.execute(), Transaction.class); + copy(other); + flush(); + + return other; + } + + /** + * Atualiza a instância do objeto com os dados mais recentes do backend. + * + * @return Instância atualizada do Objeto. + */ + public Transaction refresh() throws PagarMeException { + final Transaction other = JsonUtils.getAsObject(refreshModel(), Transaction.class); + copy(other); + flush(); + return other; + } + + private void copy(Transaction other) { + setId(other.getId()); + this.status = other.status; + this.statusReason = other.statusReason; + this.acquirerResponseCode = other.acquirerResponseCode; + this.acquirerName = other.acquirerName; + this.authorizationCode = other.authorizationCode; + this.softDescriptor = other.softDescriptor; + this.tid = other.tid; + this.nsu = other.nsu; + this.updatedAt = other.updatedAt; + this.amount = other.amount; + this.installments = other.installments; + this.cost = other.cost; + this.postbackUrl = other.postbackUrl; + this.paymentMethod = other.paymentMethod; + this.boletoUrl = other.boletoUrl; + this.boletoBarcode = other.boletoBarcode; + this.boletoExpirationDate = other.boletoExpirationDate; + this.referer = other.referer; + this.ip = other.ip; + this.subscriptionId = other.subscriptionId; + this.phone = other.phone; + this.address = other.address; + this.customer = other.customer; + this.card = other.card; + this.metadata = other.metadata; + } + + /** + * Adquirente responsável pelo processamento da transação. + */ + public enum AcquirerName { + + /** + * em ambiente de testes + */ + @SerializedName("development") + DEVELOPMENT, + + /** + * adquirente Pagar.me + */ + @SerializedName("pagarme") + PAGARME, + + @SerializedName("stone") + STONE, + + @SerializedName("cielo") + CIELO, + + @SerializedName("rede") + REDE, + + @SerializedName("mundipagg") + MUNDIPAGG + + } + + public enum Event { + + @SerializedName("transaction_status_changed") + TRANSACTION_STATUS_CHANGED + + } + + /** + * Método de pagamento + */ + public enum PaymentMethod { + + @SerializedName("credit_card") + CREDIT_CARD, + + @SerializedName("boleto") + BOLETO + + } + + /** + * Quando uma transação é criada, ela inicialmente é retornada com o status {@link #PROCESSING}. + */ + public enum Status { + + /** + * Transação sendo processada. + */ + @SerializedName("processing") + PROCESSING, + + /** + * Transação autorizada. Cliente possui saldo na conta e este valor foi reservado para futura captura, que deve + * acontecer em no máximo 5 dias. Caso a transação não seja capturada, a autorização é cancelada + * automaticamente. + */ + @SerializedName("authorized") + AUTHORIZED, + + /** + * Transação paga (autorizada e capturada). + */ + @SerializedName("paid") + PAID, + + /** + * Transação estornada. + */ + @SerializedName("refunded") + REFUNDED, + + /** + * Transação aguardando pagamento (status para transações criadas com boleto bancário). + */ + @SerializedName("waiting_payment") + WAITING_PAYMENT, + + /** + * Transação paga com boleto aguardando para ser estornada. + */ + @SerializedName("pending_refund") + PENDING_REFUND, + + /** + * Transação não autorizada. + */ + @SerializedName("refused") + REFUSED, - /** - * Transação sofreu chargeback. - */ - @SerializedName("chargedback") - CHARGEDBACK - - } + /** + * Transação sofreu chargeback. + */ + @SerializedName("chargedback") + CHARGEDBACK + + } - /** - * Motivo/agente responsável pela validação ou anulação da transação. - */ - public enum StatusReason { + /** + * Motivo/agente responsável pela validação ou anulação da transação. + */ + public enum StatusReason { - @SerializedName("acquirer") - ACQUIRER, + @SerializedName("acquirer") + ACQUIRER, - @SerializedName("antifraud") - ANTIFRAUD, + @SerializedName("antifraud") + ANTIFRAUD, - @SerializedName("internal_error") - INTERNAL_ERROR, + @SerializedName("internal_error") + INTERNAL_ERROR, - @SerializedName("no_acquirer") - NO_ACQUIRER, + @SerializedName("no_acquirer") + NO_ACQUIRER, - @SerializedName("acquirer_timeout") - ACQUIRER_TIMEOUT + @SerializedName("acquirer_timeout") + ACQUIRER_TIMEOUT - } + } } diff --git a/src/main/java/me/pagar/Transfer.java b/src/main/java/me/pagar/Transfer.java index 746553a..dfd1df8 100644 --- a/src/main/java/me/pagar/Transfer.java +++ b/src/main/java/me/pagar/Transfer.java @@ -10,145 +10,145 @@ public class Transfer extends PagarMeModel { - @Expose - @SerializedName("transaction_id") - private Integer transactionId; + @Expose + @SerializedName("transaction_id") + private Integer transactionId; - @Expose - private Integer amount; + @Expose + private Integer amount; - @Expose - private Integer fee; + @Expose + private Integer fee; - @Expose - private Type type; + @Expose + private Type type; - @Expose - private Status status; + @Expose + private Status status; - @Expose(serialize = false) - @SerializedName("funding_estimated_date") - private DateTime fundingEstimatedDate; + @Expose(serialize = false) + @SerializedName("funding_estimated_date") + private DateTime fundingEstimatedDate; - @Expose(serialize = false) - @SerializedName("funding_date") - private DateTime fundingDate; + @Expose(serialize = false) + @SerializedName("funding_date") + private DateTime fundingDate; - @Expose(serialize = false) - @SerializedName("bank_account") - private BankAccount bankAccount; + @Expose(serialize = false) + @SerializedName("bank_account") + private BankAccount bankAccount; - public BankAccount getBankAccount() { - return bankAccount; - } + public BankAccount getBankAccount() { + return bankAccount; + } - public void setBankAccount(final BankAccount bankAccount) { - this.bankAccount = bankAccount; - } + public void setBankAccount(final BankAccount bankAccount) { + this.bankAccount = bankAccount; + } - public Integer getTransactionId() { - return transactionId; - } + public Integer getTransactionId() { + return transactionId; + } - public void setTransactionId(final Integer transactionId) { - this.transactionId = transactionId; - } + public void setTransactionId(final Integer transactionId) { + this.transactionId = transactionId; + } - public Integer getAmount() { - return amount; - } + public Integer getAmount() { + return amount; + } - public void setAmount(final Integer amount) { - this.amount = amount; - } + public void setAmount(final Integer amount) { + this.amount = amount; + } - public Integer getFee() { - return fee; - } + public Integer getFee() { + return fee; + } - public void setFee(final Integer fee) { - this.fee = fee; - } + public void setFee(final Integer fee) { + this.fee = fee; + } - public Type getType() { - return type; - } + public Type getType() { + return type; + } - public void setType(final Type type) { - this.type = type; - } + public void setType(final Type type) { + this.type = type; + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - public void setStatus(final Status status) { - this.status = status; - } + public void setStatus(final Status status) { + this.status = status; + } - public DateTime getFundingEstimatedDate() { - return fundingEstimatedDate; - } + public DateTime getFundingEstimatedDate() { + return fundingEstimatedDate; + } - public void setFundingEstimatedDate(final DateTime fundingEstimatedDate) { - this.fundingEstimatedDate = fundingEstimatedDate; - } + public void setFundingEstimatedDate(final DateTime fundingEstimatedDate) { + this.fundingEstimatedDate = fundingEstimatedDate; + } - public DateTime getFundingDate() { - return fundingDate; - } + public DateTime getFundingDate() { + return fundingDate; + } - public void setFundingDate(final DateTime fundingDate) { - this.fundingDate = fundingDate; - } + public void setFundingDate(final DateTime fundingDate) { + this.fundingDate = fundingDate; + } - public Transfer(final Integer amount, final BankAccount bankAccount) { - this.amount = amount; - this.bankAccount = bankAccount; - } + public Transfer(final Integer amount, final BankAccount bankAccount) { + this.amount = amount; + this.bankAccount = bankAccount; + } - public Transfer create() throws PagarMeException { - final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s", getClassName())); - request.setParameters(JsonUtils.objectToMap(this)); + public Transfer create() throws PagarMeException { + final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s", getClassName())); + request.setParameters(JsonUtils.objectToMap(this)); - return JsonUtils.getAsObject((JsonObject) request.execute(), Transfer.class); - } + return JsonUtils.getAsObject((JsonObject) request.execute(), Transfer.class); + } - /** - * Tipo de transferencia realizada. - */ - public enum Type { + /** + * Tipo de transferencia realizada. + */ + public enum Type { - @SerializedName("ted") - TED, + @SerializedName("ted") + TED, - @SerializedName("doc") - DOC, + @SerializedName("doc") + DOC, - @SerializedName("credito_em_conta") - CREDITO_EM_CONTA - } + @SerializedName("credito_em_conta") + CREDITO_EM_CONTA + } - /** - * Status da transferência - */ - public enum Status { + /** + * Status da transferência + */ + public enum Status { - @SerializedName("pending_transfer") - PENDING_TRANSFER, + @SerializedName("pending_transfer") + PENDING_TRANSFER, - @SerializedName("transferred") - TRANSFERRED, + @SerializedName("transferred") + TRANSFERRED, - @SerializedName("failed") - FAILED, + @SerializedName("failed") + FAILED, - @SerializedName("processing") - PROCESSING, + @SerializedName("processing") + PROCESSING, - @SerializedName("canceled") - CANCELED + @SerializedName("canceled") + CANCELED - } + } } diff --git a/src/main/java/me/pagar/util/BulkAnticipationAdapter.java b/src/main/java/me/pagar/util/BulkAnticipationAdapter.java index 267797b..0b3505d 100644 --- a/src/main/java/me/pagar/util/BulkAnticipationAdapter.java +++ b/src/main/java/me/pagar/util/BulkAnticipationAdapter.java @@ -13,26 +13,26 @@ */ public class BulkAnticipationAdapter implements JsonSerializer { - @Override - public JsonElement serialize(BulkAnticipation src, Type type, JsonSerializationContext jsonSerializationContext) { + @Override + public JsonElement serialize(BulkAnticipation src, Type type, JsonSerializationContext jsonSerializationContext) { - if (src == null) { - return null; - } + if (src == null) { + return null; + } - final Gson gson = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .create(); - final String json = gson.toJson(src); + final Gson gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .create(); + final String json = gson.toJson(src); - final Map map = gson.fromJson(json, new TypeToken>() { - }.getType()); + final Map map = gson.fromJson(json, new TypeToken>() { + }.getType()); - if (null != src.getPaymentDate()) { - map.put("payment_date", src.getPaymentDate().getMillis()); - } + if (null != src.getPaymentDate()) { + map.put("payment_date", src.getPaymentDate().getMillis()); + } - return JsonUtils.getInterpreter().toJsonTree(map); - } + return JsonUtils.getInterpreter().toJsonTree(map); + } } diff --git a/src/main/java/me/pagar/util/DateTimeAdapter.java b/src/main/java/me/pagar/util/DateTimeAdapter.java index 0be6790..caa7936 100644 --- a/src/main/java/me/pagar/util/DateTimeAdapter.java +++ b/src/main/java/me/pagar/util/DateTimeAdapter.java @@ -10,23 +10,23 @@ public class DateTimeAdapter implements JsonDeserializer, JsonSerializer { - private final DateTimeFormatter formatter; - - public DateTimeAdapter() { - this.formatter = ISODateTimeFormat - .dateOptionalTimeParser() - .withZoneUTC(); - } - - @Override - public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - final String dateTime = json.getAsString(); - return Strings.isNullOrEmpty(dateTime) ? null : formatter.parseDateTime(dateTime); - } - - @Override - public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { - return src == null ? null : new JsonPrimitive(src.toString()); - } - -} \ No newline at end of file + private final DateTimeFormatter formatter; + + public DateTimeAdapter() { + this.formatter = ISODateTimeFormat + .dateOptionalTimeParser() + .withZoneUTC(); + } + + @Override + public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + final String dateTime = json.getAsString(); + return Strings.isNullOrEmpty(dateTime) ? null : formatter.parseDateTime(dateTime); + } + + @Override + public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { + return src == null ? null : new JsonPrimitive(src.toString()); + } + +} diff --git a/src/main/java/me/pagar/util/JsonUtils.java b/src/main/java/me/pagar/util/JsonUtils.java index 6c90bad..877483f 100644 --- a/src/main/java/me/pagar/util/JsonUtils.java +++ b/src/main/java/me/pagar/util/JsonUtils.java @@ -13,40 +13,40 @@ public class JsonUtils { - private static final Gson GSON_DATA_PROVIDER; - - static { - GSON_DATA_PROVIDER = new GsonBuilder() - .excludeFieldsWithoutExposeAnnotation() - .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) - .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) - .registerTypeAdapter(BulkAnticipation.class, new BulkAnticipationAdapter()) - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .setLongSerializationPolicy(LongSerializationPolicy.STRING) - .create(); - } - - public static final Gson getInterpreter() { - return GSON_DATA_PROVIDER; - } - - public static T getAsObject(JsonObject json, Class clazz) { - return GSON_DATA_PROVIDER.fromJson(json, clazz); - } - - public static Collection getAsList(JsonArray json, Type listType) { - return GSON_DATA_PROVIDER.fromJson(json, listType); - } - - public static String getAsJson(Object object) { - return GSON_DATA_PROVIDER.toJson(object); - } - - public static Map objectToMap(Object object) { - final String json = GSON_DATA_PROVIDER.toJson(object); - - return GSON_DATA_PROVIDER.fromJson(json, new TypeToken>() { - }.getType()); - } + private static final Gson GSON_DATA_PROVIDER; + + static { + GSON_DATA_PROVIDER = new GsonBuilder() + .excludeFieldsWithoutExposeAnnotation() + .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) + .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) + .registerTypeAdapter(BulkAnticipation.class, new BulkAnticipationAdapter()) + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .setLongSerializationPolicy(LongSerializationPolicy.STRING) + .create(); + } + + public static final Gson getInterpreter() { + return GSON_DATA_PROVIDER; + } + + public static T getAsObject(JsonObject json, Class clazz) { + return GSON_DATA_PROVIDER.fromJson(json, clazz); + } + + public static Collection getAsList(JsonArray json, Type listType) { + return GSON_DATA_PROVIDER.fromJson(json, listType); + } + + public static String getAsJson(Object object) { + return GSON_DATA_PROVIDER.toJson(object); + } + + public static Map objectToMap(Object object) { + final String json = GSON_DATA_PROVIDER.toJson(object); + + return GSON_DATA_PROVIDER.fromJson(json, new TypeToken>() { + }.getType()); + } } diff --git a/src/main/java/me/pagar/util/LocalDateAdapter.java b/src/main/java/me/pagar/util/LocalDateAdapter.java index bfe3667..2cc4734 100644 --- a/src/main/java/me/pagar/util/LocalDateAdapter.java +++ b/src/main/java/me/pagar/util/LocalDateAdapter.java @@ -10,23 +10,23 @@ public class LocalDateAdapter implements JsonDeserializer, JsonSerializer { - private final DateTimeFormatter formatter; - - public LocalDateAdapter() { - this.formatter = ISODateTimeFormat - .dateOptionalTimeParser() - .withZoneUTC(); - } - - @Override - public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - final String dateTime = json.getAsString(); - return Strings.isNullOrEmpty(dateTime) ? null : formatter.parseLocalDate(dateTime); - } - - @Override - public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { - return src == null ? null : new JsonPrimitive(src.toString()); - } - -} \ No newline at end of file + private final DateTimeFormatter formatter; + + public LocalDateAdapter() { + this.formatter = ISODateTimeFormat + .dateOptionalTimeParser() + .withZoneUTC(); + } + + @Override + public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + final String dateTime = json.getAsString(); + return Strings.isNullOrEmpty(dateTime) ? null : formatter.parseLocalDate(dateTime); + } + + @Override + public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { + return src == null ? null : new JsonPrimitive(src.toString()); + } + +} diff --git a/src/main/java/me/pagar/util/MapUtils.java b/src/main/java/me/pagar/util/MapUtils.java index 010ea18..b9388ad 100644 --- a/src/main/java/me/pagar/util/MapUtils.java +++ b/src/main/java/me/pagar/util/MapUtils.java @@ -13,84 +13,84 @@ public class MapUtils { - private static final String UTF_8 = "UTF-8"; + private static final String UTF_8 = "UTF-8"; - public static String mapToQuery(final Map map) { - final StringBuilder stringBuilder = new StringBuilder(); + public static String mapToQuery(final Map map) { + final StringBuilder stringBuilder = new StringBuilder(); - for (String key : map.keySet()) { + for (String key : map.keySet()) { - if (stringBuilder.length() > 0) { - stringBuilder.append("&"); - } + if (stringBuilder.length() > 0) { + stringBuilder.append("&"); + } - final Object value = map.get(key); + final Object value = map.get(key); - try { - stringBuilder.append(URLEncoder.encode(Strings.nullToEmpty(key), UTF_8)); - stringBuilder.append("="); - stringBuilder.append(null == value ? "" : URLEncoder.encode(Strings.nullToEmpty(String.valueOf(value)), UTF_8)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("This method requires UTF-8 encoding support", e); - } + try { + stringBuilder.append(URLEncoder.encode(Strings.nullToEmpty(key), UTF_8)); + stringBuilder.append("="); + stringBuilder.append(null == value ? "" : URLEncoder.encode(Strings.nullToEmpty(String.valueOf(value)), UTF_8)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("This method requires UTF-8 encoding support", e); + } - } + } - return stringBuilder.toString(); - } + return stringBuilder.toString(); + } - public static Map queryToMap(final String query) { - final Map map = new HashMap(); - final String[] keyValuePairs = query.split("&"); + public static Map queryToMap(final String query) { + final Map map = new HashMap(); + final String[] keyValuePairs = query.split("&"); - for (String KeyValuePair : keyValuePairs) { - final String[] keyValue = KeyValuePair.split("="); + for (String KeyValuePair : keyValuePairs) { + final String[] keyValue = KeyValuePair.split("="); - if (keyValue.length > 0) { - try { - map.put(URLDecoder.decode(keyValue[0], UTF_8), keyValue.length == 2 ? keyValue[1] : null); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("This method requires UTF-8 encoding support", e); - } - } + if (keyValue.length > 0) { + try { + map.put(URLDecoder.decode(keyValue[0], UTF_8), keyValue.length == 2 ? keyValue[1] : null); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("This method requires UTF-8 encoding support", e); + } + } - } + } - return map; - } + return map; + } - public static Map objectToMap(final Object obj) { - return objectToMap(obj, new ArrayList()); - } + public static Map objectToMap(final Object obj) { + return objectToMap(obj, new ArrayList()); + } - public static Map objectToMap(final Object obj, final List blacklist) { - final Map result = new LinkedHashMap(); + public static Map objectToMap(final Object obj, final List blacklist) { + final Map result = new LinkedHashMap(); - // XXX always ignore class and className attribute - blacklist.addAll(Arrays.asList("class", "className")); + // XXX always ignore class and className attribute + blacklist.addAll(Arrays.asList("class", "className")); - try { - final BeanInfo info = Introspector.getBeanInfo(obj.getClass()); + try { + final BeanInfo info = Introspector.getBeanInfo(obj.getClass()); - for (PropertyDescriptor pd : info.getPropertyDescriptors()) { - final Method reader = pd.getReadMethod(); + for (PropertyDescriptor pd : info.getPropertyDescriptors()) { + final Method reader = pd.getReadMethod(); - if (reader != null && (blacklist.size() == 0 || !blacklist.contains(pd.getName()))) { - final Object value = reader.invoke(obj); + if (reader != null && (blacklist.size() == 0 || !blacklist.contains(pd.getName()))) { + final Object value = reader.invoke(obj); - if (null == value || - value instanceof Number || - value instanceof CharSequence || - value instanceof Boolean) { - result.put(pd.getName(), value); - } else { - result.put(pd.getName(), objectToMap(value)); - } - } - } + if (null == value || + value instanceof Number || + value instanceof CharSequence || + value instanceof Boolean) { + result.put(pd.getName(), value); + } else { + result.put(pd.getName(), objectToMap(value)); + } + } + } - } catch (Exception ignored) { - } - return result; - } + } catch (Exception ignored) { + } + return result; + } } diff --git a/src/main/java/me/pagar/util/PagarMeSSLSocketFactory.java b/src/main/java/me/pagar/util/PagarMeSSLSocketFactory.java new file mode 100644 index 0000000..03d5ff1 --- /dev/null +++ b/src/main/java/me/pagar/util/PagarMeSSLSocketFactory.java @@ -0,0 +1,337 @@ +package me.pagar.util; + +import me.pagar.PagarMe; +import org.bouncycastle.crypto.tls.*; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; + +import javax.net.ssl.*; +import javax.security.cert.X509Certificate; +import java.io.*; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.security.Principal; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.Hashtable; +import java.util.LinkedList; +import java.util.List; + +public class PagarMeSSLSocketFactory extends SSLSocketFactory { + + static { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + } + + public PagarMeSSLSocketFactory() { + System.setProperty("https.protocols", "TLSv1.2"); + } + + private java.security.cert.Certificate getRequiredCert(final CertificateFactory cf) + throws IOException, CertificateException { + PemReader reader = null; + try { + // read local cert copy + final InputStream certFile = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("pagarme.crt"); + + reader = new PemReader(new InputStreamReader(certFile)); + final PemObject pem = reader.readPemObject(); + final ByteArrayInputStream bais = new ByteArrayInputStream(pem.getContent()); + // will always return 1 + final java.security.cert.X509Certificate cert = + (java.security.cert.X509Certificate) cf.generateCertificates(bais).iterator().next(); + // ensure it is valid + cert.checkValidity(); + return cert; + } finally { + if (null != reader) { + reader.close(); + } + } + } + + public Socket createSocket(Socket s, final String host, final int port, final boolean autoClose) throws IOException { + if (s == null) { + s = new Socket(); + } + + if (!s.isConnected()) { + s.connect(new InetSocketAddress(host, port)); + } + + final TlsClientProtocol tlsClientProtocol = new TlsClientProtocol( + s.getInputStream(), s.getOutputStream(), + new SecureRandom()); + + return _createSSLSocket(host, tlsClientProtocol); + } + + public String[] getDefaultCipherSuites() { + return null; + } + + public String[] getSupportedCipherSuites() { + return null; + } + + public Socket createSocket(String host, int port) { + throw new UnsupportedOperationException(); + } + + public Socket createSocket(InetAddress host, int port) { + throw new UnsupportedOperationException(); + } + + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) { + throw new UnsupportedOperationException(); + } + + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) { + throw new UnsupportedOperationException(); + } + + private SSLSocket _createSSLSocket(final String host, final TlsClientProtocol tlsClientProtocol) { + return new SSLSocket() { + private java.security.cert.Certificate[] peerCerts; + + public InputStream getInputStream() { + return tlsClientProtocol.getInputStream(); + } + + public OutputStream getOutputStream() { + return tlsClientProtocol.getOutputStream(); + } + + public synchronized void close() throws IOException { + tlsClientProtocol.close(); + } + + public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { + } + + public boolean getEnableSessionCreation() { + return false; + } + + public String[] getEnabledCipherSuites() { + return null; + } + + public String[] getEnabledProtocols() { + return null; + } + + public boolean getNeedClientAuth() { + return false; + } + + public SSLSession getSession() { + return new SSLSession() { + + public int getApplicationBufferSize() { + return 0; + } + + public String getCipherSuite() { + throw new UnsupportedOperationException(); + } + + public long getCreationTime() { + throw new UnsupportedOperationException(); + } + + public byte[] getId() { + throw new UnsupportedOperationException(); + } + + public long getLastAccessedTime() { + throw new UnsupportedOperationException(); + } + + public java.security.cert.Certificate[] getLocalCertificates() { + throw new UnsupportedOperationException(); + } + + public Principal getLocalPrincipal() { + throw new UnsupportedOperationException(); + } + + public int getPacketBufferSize() { + throw new UnsupportedOperationException(); + } + + public X509Certificate[] getPeerCertificateChain() { + return null; + } + + public java.security.cert.Certificate[] getPeerCertificates() { + return peerCerts; + } + + public String getPeerHost() { + throw new UnsupportedOperationException(); + } + + public int getPeerPort() { + return 0; + } + + public Principal getPeerPrincipal() { + return null; + } + + public String getProtocol() { + throw new UnsupportedOperationException(); + } + + public SSLSessionContext getSessionContext() { + throw new UnsupportedOperationException(); + } + + public Object getValue(String arg0) { + throw new UnsupportedOperationException(); + } + + public String[] getValueNames() { + throw new UnsupportedOperationException(); + } + + public void invalidate() { + throw new UnsupportedOperationException(); + } + + public boolean isValid() { + throw new UnsupportedOperationException(); + } + + public void putValue(String arg0, Object arg1) { + throw new UnsupportedOperationException(); + } + + public void removeValue(String arg0) { + throw new UnsupportedOperationException(); + } + }; + } + + public String[] getSupportedProtocols() { + return null; + } + + public boolean getUseClientMode() { + return false; + } + + public boolean getWantClientAuth() { + return false; + } + + public void removeHandshakeCompletedListener( + HandshakeCompletedListener arg0) { + } + + public void setEnableSessionCreation(boolean flag) { + } + + public void setEnabledCipherSuites(String[] suites) { + } + + public void setEnabledProtocols(String[] protocols) { + } + + public void setNeedClientAuth(boolean need) { + } + + public void setUseClientMode(boolean mode) { + } + + public void setWantClientAuth(boolean want) { + } + + public String[] getSupportedCipherSuites() { + return null; + } + + public void startHandshake() throws IOException { + tlsClientProtocol.connect(new DefaultTlsClient() { + + @SuppressWarnings("unchecked") + public Hashtable getClientExtensions() throws IOException { + Hashtable clientExtensions = super.getClientExtensions(); + if (clientExtensions == null) { + clientExtensions = new Hashtable(); + } + + // Add host_name + final byte[] hostName = host.getBytes(); + + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final DataOutputStream dos = new DataOutputStream(baos); + dos.writeShort(hostName.length + 3); + dos.writeByte(0); + dos.writeShort(hostName.length); + dos.write(hostName); + dos.close(); + + clientExtensions.put(ExtensionType.server_name, baos.toByteArray()); + return clientExtensions; + } + + public TlsAuthentication getAuthentication() { + return new TlsAuthentication() { + + public void notifyServerCertificate( + org.bouncycastle.crypto.tls.Certificate serverCertificate) throws IOException { + try { + final CertificateFactory cf = CertificateFactory.getInstance("X.509"); + final java.security.cert.Certificate requiredCert = getRequiredCert(cf); + + final List certs = new LinkedList(); + boolean trustedCertificate = false; + for (org.bouncycastle.asn1.x509.Certificate c : serverCertificate.getCertificateList()) { + java.security.cert.Certificate cert = + cf.generateCertificate(new ByteArrayInputStream(c.getEncoded())); + certs.add(cert); + + if (cert instanceof java.security.cert.X509Certificate) { + java.security.cert.X509Certificate x509 = + (java.security.cert.X509Certificate) cert; + x509.checkValidity(); + + if (null == requiredCert || + !PagarMe.isSslPinningEnabled() || + x509.equals(requiredCert)) { + trustedCertificate = true; + break; + } + } + } + + if (!trustedCertificate) { + throw new IOException("Invalid certificate chain. Possible SSL proxy cert being used."); + } + + peerCerts = certs.toArray(new java.security.cert.Certificate[0]); + } catch (Exception e) { + throw new IOException(e); + } + } + + public TlsCredentials getClientCredentials(CertificateRequest certificateRequest) { + return null; + } + }; + } + }); + } + }; + } +} diff --git a/src/test/java/me/pagar/BalanceTest.java b/src/test/java/me/pagar/BalanceTest.java index 601b7d8..6a37b84 100644 --- a/src/test/java/me/pagar/BalanceTest.java +++ b/src/test/java/me/pagar/BalanceTest.java @@ -6,19 +6,19 @@ public class BalanceTest extends BaseTest { - private Balance balance; + private Balance balance; - @Before - public void setUp() { - super.setUp(); - balance = new Balance(); - } + @Before + public void setUp() { + super.setUp(); + balance = new Balance(); + } - @Test - public void testRefresh() throws Throwable { - balance.refresh(); - Assert.assertNotNull(balance.getAvailable()); - } + @Test + public void testRefresh() throws Throwable { + balance.refresh(); + Assert.assertNotNull(balance.getAvailable()); + } } diff --git a/src/test/java/me/pagar/BankAccountTest.java b/src/test/java/me/pagar/BankAccountTest.java index 2e51fcd..39c2c33 100644 --- a/src/test/java/me/pagar/BankAccountTest.java +++ b/src/test/java/me/pagar/BankAccountTest.java @@ -9,30 +9,30 @@ public class BankAccountTest extends BaseTest { - private BankAccount bankAccount; - - @Before - public void setUp() { - super.setUp(); - bankAccount = new BankAccount(); - } - - @Test - public void testFindAll() throws Throwable { - final Collection bankAccounts = bankAccount.find(5, 1); - Assert.assertNotEquals(0, bankAccounts.size()); - } - - @Test - public void testSave() throws Throwable { - bankAccount.setBankCode("341"); - bankAccount.setAgencia("8888"); - bankAccount.setConta("34123"); - bankAccount.setContaDv("1"); - bankAccount.setDocumentType(BankAccount.DocumentType.CPF); - bankAccount.setDocumentNumber("75068255971"); - bankAccount.setLegalName("JOAO JOSE JOAQUIM"); - bankAccount.save(); - } + private BankAccount bankAccount; + + @Before + public void setUp() { + super.setUp(); + bankAccount = new BankAccount(); + } + + @Test + public void testFindAll() throws Throwable { + final Collection bankAccounts = bankAccount.find(5, 1); + Assert.assertNotEquals(0, bankAccounts.size()); + } + + @Test + public void testSave() throws Throwable { + bankAccount.setBankCode("341"); + bankAccount.setAgencia("8888"); + bankAccount.setConta("34123"); + bankAccount.setContaDv("1"); + bankAccount.setDocumentType(BankAccount.DocumentType.CPF); + bankAccount.setDocumentNumber("75068255971"); + bankAccount.setLegalName("JOAO JOSE JOAQUIM"); + bankAccount.save(); + } } diff --git a/src/test/java/me/pagar/BaseTest.java b/src/test/java/me/pagar/BaseTest.java index 4d1fa76..ac6ae96 100644 --- a/src/test/java/me/pagar/BaseTest.java +++ b/src/test/java/me/pagar/BaseTest.java @@ -4,14 +4,14 @@ public abstract class BaseTest { - public void setUp() { - String apiKey = System.getenv("PAGARME_API_KEY"); + public void setUp() { + String apiKey = System.getenv("PAGARME_API_KEY"); - if (Strings.isNullOrEmpty(apiKey)) { - apiKey = "ak_test_Rw4JR98FmYST2ngEHtMvVf5QJW7Eoo"; - } + if (Strings.isNullOrEmpty(apiKey)) { + apiKey = "ak_test_Rw4JR98FmYST2ngEHtMvVf5QJW7Eoo"; + } - PagarMe.init(apiKey); - } + PagarMe.init(apiKey); + } } diff --git a/src/test/java/me/pagar/CardTest.java b/src/test/java/me/pagar/CardTest.java index 2fc9f21..e08cc3e 100644 --- a/src/test/java/me/pagar/CardTest.java +++ b/src/test/java/me/pagar/CardTest.java @@ -8,57 +8,57 @@ public class CardTest extends BaseTest { - private final int TRANSACTION_ID = 598075; + private final int TRANSACTION_ID = 598075; - private Card card; + private Card card; - private Transaction transaction; + private Transaction transaction; - @Before - public void setUp() { - super.setUp(); - card = new Card(); - transaction = new Transaction(); - transaction.setId(TRANSACTION_ID); - } + @Before + public void setUp() { + super.setUp(); + card = new Card(); + transaction = new Transaction(); + transaction.setId(TRANSACTION_ID); + } - @Test - public void testFindAll() throws Throwable { - Collection cards = card.list(); - Assert.assertNotEquals(0, cards.size()); - } + @Test + public void testFindAll() throws Throwable { + Collection cards = card.list(); + Assert.assertNotEquals(0, cards.size()); + } - @Test - public void testEncrypt() throws Throwable { - card = new Card("4901720080344448", - "Aardvark Silva", - "1213", - "314"); + @Test + public void testEncrypt() throws Throwable { + card = new Card("4901720080344448", + "Aardvark Silva", + "1213", + "314"); - final CardHashKey cardHashKey = transaction.cardHashKey(); - Assert.assertNotNull(cardHashKey); + final CardHashKey cardHashKey = transaction.cardHashKey(); + Assert.assertNotNull(cardHashKey); - final String encryptedCreditCard = card.encrypt(cardHashKey); + final String encryptedCreditCard = card.encrypt(cardHashKey); - Assert.assertNotNull(encryptedCreditCard); + Assert.assertNotNull(encryptedCreditCard); - card.save(); - Assert.assertNotNull(card.getId()); - } + card.save(); + Assert.assertNotNull(card.getId()); + } - @Test - public void testEncryptWithNullData() throws Throwable { - card = new Card("4901720080344448", - "Aardvark Silva", - "1213", - null); + @Test + public void testEncryptWithNullData() throws Throwable { + card = new Card("4901720080344448", + "Aardvark Silva", + "1213", + null); - final CardHashKey cardHashKey = transaction.cardHashKey(); - Assert.assertNotNull(cardHashKey); + final CardHashKey cardHashKey = transaction.cardHashKey(); + Assert.assertNotNull(cardHashKey); - final String encryptedCreditCard = card.encrypt(cardHashKey); + final String encryptedCreditCard = card.encrypt(cardHashKey); - Assert.assertNull(encryptedCreditCard); - } + Assert.assertNull(encryptedCreditCard); + } } diff --git a/src/test/java/me/pagar/CustomerTest.java b/src/test/java/me/pagar/CustomerTest.java index fa21da5..15a5488 100644 --- a/src/test/java/me/pagar/CustomerTest.java +++ b/src/test/java/me/pagar/CustomerTest.java @@ -9,54 +9,54 @@ public class CustomerTest extends BaseTest { - private final String CUSTOMER_NAME = "Test Create Customer", - CUSTOMER_DOCUMENT_NUMBER = "11111111111", - CUSTOMER_EMAIL = "customer1@pagar.me", - CUSTOMER_ADDRESS_STREET = "Rua Jose da Silva", - CUSTOMER_ADDRESS_STREET_NUMBER = "123", - CUSTOMER_ADDRESS_COMPLEMENTARY = "Casa", - CUSTOMER_ADDRESS_NEIGHBORHOOD = "Interlagos", - CUSTOMER_ADDRESS_ZIP_CODE = "04840110", - CUSTOMER_PHONE_DDD = "11", - CUSTOMER_PHONE_NUMBER = "55284132"; - - private final LocalDate CUSTOMER_BORN_AT = LocalDate.parse("1981-03-23"); - - private Customer customer; - - @Before - public void setUp() { - super.setUp(); - customer = new Customer(); - } - - @Test - public void testList() throws Throwable { - final Collection customers = customer.list(); - Assert.assertFalse(customers.isEmpty()); - } - - @Test - public void testSave() throws Throwable { - final Address address = new Address(CUSTOMER_ADDRESS_STREET, CUSTOMER_ADDRESS_STREET_NUMBER, - CUSTOMER_ADDRESS_NEIGHBORHOOD, CUSTOMER_ADDRESS_ZIP_CODE); - address.setComplementary(CUSTOMER_ADDRESS_COMPLEMENTARY); - - final Phone phone = new Phone(CUSTOMER_PHONE_DDD, CUSTOMER_PHONE_NUMBER); - - customer.setName(CUSTOMER_NAME); - customer.setEmail(CUSTOMER_EMAIL); - customer.setDocumentNumber(CUSTOMER_DOCUMENT_NUMBER); - customer.setBornAt(CUSTOMER_BORN_AT); - - customer.setAddress(address); - customer.setPhone(phone); - customer = customer.save(); - - Assert.assertFalse(customer.getAddresses().isEmpty()); - Assert.assertFalse(customer.getPhones().isEmpty()); - Assert.assertNotNull(customer.getId()); - } + private final String CUSTOMER_NAME = "Test Create Customer", + CUSTOMER_DOCUMENT_NUMBER = "11111111111", + CUSTOMER_EMAIL = "customer1@pagar.me", + CUSTOMER_ADDRESS_STREET = "Rua Jose da Silva", + CUSTOMER_ADDRESS_STREET_NUMBER = "123", + CUSTOMER_ADDRESS_COMPLEMENTARY = "Casa", + CUSTOMER_ADDRESS_NEIGHBORHOOD = "Interlagos", + CUSTOMER_ADDRESS_ZIP_CODE = "04840110", + CUSTOMER_PHONE_DDD = "11", + CUSTOMER_PHONE_NUMBER = "55284132"; + + private final LocalDate CUSTOMER_BORN_AT = LocalDate.parse("1981-03-23"); + + private Customer customer; + + @Before + public void setUp() { + super.setUp(); + customer = new Customer(); + } + + @Test + public void testList() throws Throwable { + final Collection customers = customer.list(); + Assert.assertFalse(customers.isEmpty()); + } + + @Test + public void testSave() throws Throwable { + final Address address = new Address(CUSTOMER_ADDRESS_STREET, CUSTOMER_ADDRESS_STREET_NUMBER, + CUSTOMER_ADDRESS_NEIGHBORHOOD, CUSTOMER_ADDRESS_ZIP_CODE); + address.setComplementary(CUSTOMER_ADDRESS_COMPLEMENTARY); + + final Phone phone = new Phone(CUSTOMER_PHONE_DDD, CUSTOMER_PHONE_NUMBER); + + customer.setName(CUSTOMER_NAME); + customer.setEmail(CUSTOMER_EMAIL); + customer.setDocumentNumber(CUSTOMER_DOCUMENT_NUMBER); + customer.setBornAt(CUSTOMER_BORN_AT); + + customer.setAddress(address); + customer.setPhone(phone); + customer = customer.save(); + + Assert.assertFalse(customer.getAddresses().isEmpty()); + Assert.assertFalse(customer.getPhones().isEmpty()); + Assert.assertNotNull(customer.getId()); + } } diff --git a/src/test/java/me/pagar/PagarMeTest.java b/src/test/java/me/pagar/PagarMeTest.java index 01b8652..8557ef4 100644 --- a/src/test/java/me/pagar/PagarMeTest.java +++ b/src/test/java/me/pagar/PagarMeTest.java @@ -8,18 +8,18 @@ public class PagarMeTest extends BaseTest { - private String payload = "{\"sample\":\"payload\",\"value\":true}"; + private String payload = "{\"sample\":\"payload\",\"value\":true}"; - @Before - public void setUp() { - super.setUp(); - } + @Before + public void setUp() { + super.setUp(); + } - @Test - public void testValidateRequestSignature() throws Throwable { - assertTrue(PagarMe.validateRequestSignature(payload, "sha1=7820fcb6d03ec8f721c14596654d24623af9e7de")); + @Test + public void testValidateRequestSignature() throws Throwable { + assertTrue(PagarMe.validateRequestSignature(payload, "sha1=7820fcb6d03ec8f721c14596654d24623af9e7de")); - assertFalse(PagarMe.validateRequestSignature(payload, "sha1=hash_errado")); - } + assertFalse(PagarMe.validateRequestSignature(payload, "sha1=hash_errado")); + } } diff --git a/src/test/java/me/pagar/RecipientTest.java b/src/test/java/me/pagar/RecipientTest.java index ee46054..5a6752d 100644 --- a/src/test/java/me/pagar/RecipientTest.java +++ b/src/test/java/me/pagar/RecipientTest.java @@ -10,72 +10,72 @@ public class RecipientTest extends BaseTest { - private static final String RECIPIENT_ID_1 = "re_cjbc7o5rm01kz266exv7kx4ru"; - private static final String RECIPIENT_ID_2 = "re_cjbc7nr0f01ks266evugph5dc"; - - private Recipient recipient; - - @Before - public void setUp() { - super.setUp(); - recipient = new Recipient(); - recipient.setId(RECIPIENT_ID_1); - } - - @Test - public void testFindAll() throws Throwable { - final Collection recipients = recipient.find(5, 1); - Assert.assertNotEquals(0, recipients.size()); - } - - @Test - public void testRefresh() throws Throwable { - recipient.refresh(); - Assert.assertNotNull(recipient.getBankAccount()); - - Assert.assertEquals(17661945, recipient.getBankAccount().getId().longValue()); - } - - @Test - public void testSave() throws Throwable { - recipient.setId(RECIPIENT_ID_2); - recipient.refresh(); - - recipient.setTransferDay(1); - recipient.setTransferEnabled(false); - recipient.setTransferInterval(Recipient.TransferInterval.WEEKLY); - - final BankAccount bankAccount = recipient.getBankAccount(); - bankAccount.setBankCode("341"); - bankAccount.setAgencia("0932"); - bankAccount.setAgenciaDv("5"); - bankAccount.setConta("58054"); - bankAccount.setContaDv("1"); - - recipient.save(); - - Assert.assertEquals("341", recipient.getBankAccount().getBankCode()); - } - - @Test(expected = PagarMeException.class) - public void testCreateBulkAnticipation() throws Throwable { - BulkAnticipation anticipation = new BulkAnticipation(DateTime.now(DateTimeZone.UTC).plusDays(7), - BulkAnticipation.Timeframe.START, 100, true); //valor em centavos - - anticipation = recipient.bulkAnticipations(anticipation); - Assert.assertNotNull(anticipation.getId()); - } - - @Test(expected = PagarMeException.class) - public void testCreateBulkAnticipationLimits() throws Throwable { - final BulkAnticipation.Limits limits = recipient.bulkAnticipationsLimits(); - Assert.assertNotNull(limits); - } - - @Test - public void testFindAllBulkAnticipations() throws Throwable { - final Collection anticipations = recipient.bulkAnticipations(); - Assert.assertEquals(0, anticipations.size()); - } + private static final String RECIPIENT_ID_1 = "re_cjbc7o5rm01kz266exv7kx4ru"; + private static final String RECIPIENT_ID_2 = "re_cjbc7nr0f01ks266evugph5dc"; + + private Recipient recipient; + + @Before + public void setUp() { + super.setUp(); + recipient = new Recipient(); + recipient.setId(RECIPIENT_ID_1); + } + + @Test + public void testFindAll() throws Throwable { + final Collection recipients = recipient.find(5, 1); + Assert.assertNotEquals(0, recipients.size()); + } + + @Test + public void testRefresh() throws Throwable { + recipient.refresh(); + Assert.assertNotNull(recipient.getBankAccount()); + + Assert.assertEquals(17661945, recipient.getBankAccount().getId().longValue()); + } + + @Test + public void testSave() throws Throwable { + recipient.setId(RECIPIENT_ID_2); + recipient.refresh(); + + recipient.setTransferDay(1); + recipient.setTransferEnabled(false); + recipient.setTransferInterval(Recipient.TransferInterval.WEEKLY); + + final BankAccount bankAccount = recipient.getBankAccount(); + bankAccount.setBankCode("341"); + bankAccount.setAgencia("0932"); + bankAccount.setAgenciaDv("5"); + bankAccount.setConta("58054"); + bankAccount.setContaDv("1"); + + recipient.save(); + + Assert.assertEquals("341", recipient.getBankAccount().getBankCode()); + } + + @Test(expected = PagarMeException.class) + public void testCreateBulkAnticipation() throws Throwable { + BulkAnticipation anticipation = new BulkAnticipation(DateTime.now(DateTimeZone.UTC).plusDays(7), + BulkAnticipation.Timeframe.START, 100, true); //valor em centavos + + anticipation = recipient.bulkAnticipations(anticipation); + Assert.assertNotNull(anticipation.getId()); + } + + @Test(expected = PagarMeException.class) + public void testCreateBulkAnticipationLimits() throws Throwable { + final BulkAnticipation.Limits limits = recipient.bulkAnticipationsLimits(); + Assert.assertNotNull(limits); + } + + @Test + public void testFindAllBulkAnticipations() throws Throwable { + final Collection anticipations = recipient.bulkAnticipations(); + Assert.assertEquals(0, anticipations.size()); + } } diff --git a/src/test/java/me/pagar/TransactionTest.java b/src/test/java/me/pagar/TransactionTest.java index 5a4af3a..c895d3a 100644 --- a/src/test/java/me/pagar/TransactionTest.java +++ b/src/test/java/me/pagar/TransactionTest.java @@ -9,57 +9,57 @@ public class TransactionTest extends BaseTest { - private final int TRANSACTION_ID = 598075; + private final int TRANSACTION_ID = 598075; - private Transaction transaction; + private Transaction transaction; - @Before - public void setUp() { - super.setUp(); - transaction = new Transaction(); - transaction.setId(TRANSACTION_ID); - } + @Before + public void setUp() { + super.setUp(); + transaction = new Transaction(); + transaction.setId(TRANSACTION_ID); + } - @Test - public void testFindAll() throws Throwable { - Collection transactions = transaction.list(5, 1); - Assert.assertNotEquals(0, transactions.size()); - } + @Test + public void testFindAll() throws Throwable { + Collection transactions = transaction.list(5, 1); + Assert.assertNotEquals(0, transactions.size()); + } - @Test - public void testCardHashKey() throws Throwable { - CardHashKey cardHashKey = transaction.cardHashKey(); - Assert.assertNotNull(cardHashKey); - } + @Test + public void testCardHashKey() throws Throwable { + CardHashKey cardHashKey = transaction.cardHashKey(); + Assert.assertNotNull(cardHashKey); + } - @Test - public void testTransactions() throws Throwable { - Collection transactions = transaction.list(); - Assert.assertNotEquals(0, transactions.size()); - } + @Test + public void testTransactions() throws Throwable { + Collection transactions = transaction.list(); + Assert.assertNotEquals(0, transactions.size()); + } - @Test - public void testAntifraudAnalysises() throws Throwable { - Collection antifraudAnalysises = transaction.antifraudAnalysises(); - Assert.assertEquals(0, antifraudAnalysises.size()); - } + @Test + public void testAntifraudAnalysises() throws Throwable { + Collection antifraudAnalysises = transaction.antifraudAnalysises(); + Assert.assertEquals(0, antifraudAnalysises.size()); + } - @Test - public void testPayables() throws Throwable { - Collection payables = transaction.payables(); - Assert.assertEquals(0, payables.size()); - } + @Test + public void testPayables() throws Throwable { + Collection payables = transaction.payables(); + Assert.assertEquals(0, payables.size()); + } - @Test - public void testPostbacks() throws Throwable { - Collection postbacks = transaction.postbacks(); - Assert.assertEquals(0, postbacks.size()); - } + @Test + public void testPostbacks() throws Throwable { + Collection postbacks = transaction.postbacks(); + Assert.assertEquals(0, postbacks.size()); + } - @Test - public void testSplitRules() throws Throwable { - Collection splitRules = transaction.splitRules(); - Assert.assertEquals(0, splitRules.size()); - } + @Test + public void testSplitRules() throws Throwable { + Collection splitRules = transaction.splitRules(); + Assert.assertEquals(0, splitRules.size()); + } } diff --git a/src/test/java/me/pagar/util/MapUtilsTest.java b/src/test/java/me/pagar/util/MapUtilsTest.java index 31299af..932246e 100644 --- a/src/test/java/me/pagar/util/MapUtilsTest.java +++ b/src/test/java/me/pagar/util/MapUtilsTest.java @@ -11,61 +11,61 @@ public class MapUtilsTest extends BaseTest { - private String query = "keyWithValue=123&keyWithoutValue="; - - private String queryEscaped = "keyWith%5Bvalue%5D=123&keyWithout%5Bvalue%5D="; - - @Before - public void setUp() { - super.setUp(); - } - - @Test - public void testMapToQuery() throws Exception { - final Map values = new LinkedHashMap(); - values.put("keyWithValue", "123"); - values.put("keyWithoutValue", ""); - - Assert.assertEquals(query, MapUtils.mapToQuery(values)); - } - - @Test - public void testMapToQueryEscaped() throws Exception { - final Map values = new LinkedHashMap(); - values.put("keyWith[value]", "123"); - values.put("keyWithout[value]", null); - - Assert.assertEquals(queryEscaped, MapUtils.mapToQuery(values)); - } - - @Test - public void testQueryToMap() throws Exception { - final Map values = MapUtils.queryToMap(query); - - Assert.assertEquals("123", values.get("keyWithValue")); - Assert.assertNull(values.get("keyWithoutValue")); - } - - @Test - public void testQueryToMapEscaped() throws Exception { - final Map values = MapUtils.queryToMap(queryEscaped); - - Assert.assertEquals("123", values.get("keyWith[value]")); - Assert.assertNull(values.get("keyWithout[value]")); - } - - @Test - public void testObjectToMap() throws Exception { - final Balance balance = new Balance(); - - final Map expected = new LinkedHashMap(); - expected.put("available", null); - expected.put("createdAt", null); - expected.put("id", null); - expected.put("transferred", null); - expected.put("waitingFunds", null); - - Assert.assertEquals(expected, MapUtils.objectToMap(balance)); - } + private String query = "keyWithValue=123&keyWithoutValue="; + + private String queryEscaped = "keyWith%5Bvalue%5D=123&keyWithout%5Bvalue%5D="; + + @Before + public void setUp() { + super.setUp(); + } + + @Test + public void testMapToQuery() throws Exception { + final Map values = new LinkedHashMap(); + values.put("keyWithValue", "123"); + values.put("keyWithoutValue", ""); + + Assert.assertEquals(query, MapUtils.mapToQuery(values)); + } + + @Test + public void testMapToQueryEscaped() throws Exception { + final Map values = new LinkedHashMap(); + values.put("keyWith[value]", "123"); + values.put("keyWithout[value]", null); + + Assert.assertEquals(queryEscaped, MapUtils.mapToQuery(values)); + } + + @Test + public void testQueryToMap() throws Exception { + final Map values = MapUtils.queryToMap(query); + + Assert.assertEquals("123", values.get("keyWithValue")); + Assert.assertNull(values.get("keyWithoutValue")); + } + + @Test + public void testQueryToMapEscaped() throws Exception { + final Map values = MapUtils.queryToMap(queryEscaped); + + Assert.assertEquals("123", values.get("keyWith[value]")); + Assert.assertNull(values.get("keyWithout[value]")); + } + + @Test + public void testObjectToMap() throws Exception { + final Balance balance = new Balance(); + + final Map expected = new LinkedHashMap(); + expected.put("available", null); + expected.put("createdAt", null); + expected.put("id", null); + expected.put("transferred", null); + expected.put("waitingFunds", null); + + Assert.assertEquals(expected, MapUtils.objectToMap(balance)); + } } diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index b888b58..0dc2588 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -1,6 +1,5 @@ # Root logger option log4j.rootLogger=TRACE, file, stdout - # Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=target/logging.log @@ -8,9 +7,8 @@ log4j.appender.file.MaxFileSize=10MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n