diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..4be275b4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: java +jdk: + - oraclejdk7 + - openjdk7 + - openjdk6 +notifications: + recipients: + - DL-PP-Platform-Java-SDK@ebay.com + on_success: change \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 33d10cd9..c8f7680b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,16 @@ CHANGELOG ========= +V0.7.0 (May 30, 2013) +----------------------- + * Added support for Auth and Capture APIs + * Types Modified to match the API Spec -V0.5.2 (March 07, 2013) +V0.6.0 (April 26, 2013) ----------------------- + * Added dynamic configuration support for API calls +V0.5.2 (March 07, 2013) +----------------------- * Initial Release + diff --git a/README.md b/README.md index a2b6cb62..18f4313f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ -This repository contains java sdk and samples for REST API. +## PayPal REST API Java SDK [![Build Status](https://travis-ci.org/paypal/rest-api-sdk-java.png?branch=master)](https://travis-ci.org/paypal/rest-api-sdk-java) +This repository contains Java SDK and samples for REST API. Prerequisites: --------------- @@ -23,7 +24,7 @@ SDK Integration: com.paypal.sdk rest-api-sdk - 0.5.2 + 0.7.0 @@ -31,40 +32,49 @@ To make an API call: -------------------- * Import stub classes into your code. For example, - import com.paypal.api.payments.* + ```java + import com.paypal.api.payments.* + ``` * Copy the configuration file `sdk_config.properties` in `rest-api-sample/src/test/resources` folder to your application `src/main/resources`. And load it as a classloader resource, - InputStream is = PaymentWithCreditCardServlet.class.getResourceAsStream("/sdk_config.properties"); + ```java + InputStream is = PaymentWithCreditCardServlet.class.getResourceAsStream("/sdk_config.properties"); + ``` * Or load config file from any custom location using absolute path with the below method calls as required, - - Payment.initConfig(new File("../sdk_config.properties")); - Or - Payment.initConfig(new InputStream(new File("../sdk_config.properties"))); - Or - Payment.initConfig(new Properties().load(new InputStream(new File("../sdk_config.properties")))); + ```java + Payment.initConfig(new File("../sdk_config.properties")); + Or + Payment.initConfig(new InputStream(new File("../sdk_config.properties"))); + Or + Payment.initConfig(new Properties().load(new InputStream(new File("../sdk_config.properties")))); + ``` * Create `accesstoken` from `clientID` and `clientSecret` using `OAuthTokenCredential` - String accessToken = new OAuthTokenCredential(clientID, clientSecret).getAccessToken(); + ```java + String accessToken = new OAuthTokenCredential(clientID, clientSecret).getAccessToken(); + ``` * Depending on the context of API calls, calling method may be static or non-static (For example, most `GET` http methods are created as `static` methods within the resource). In all API calls, we need to pass `accessToken` created above as argument as shown below, * If it is static, invoke it as a class method as like - Payment.get(accessToken, paymentID); + ```java + Payment.get(accessToken, paymentID); + ``` * If it is non-static, invoke it using resource object as like below. The API call takes a APIContext object in the place of AccessToken, APIContext object encapsulates Access Token and Request ID (used for idempotency). - APIContext apiContext = new APIContext(accessToken); - (OR) - APIContext apiContext = new APIContext(accessToken, requestId); - Payment payment = new Payment(); - payment.setIntent("sale"); - ... - ... - ... - payment.create(apiContext); + ```java + APIContext apiContext = new APIContext(accessToken); + (OR) + APIContext apiContext = new APIContext(accessToken, requestId); + Payment payment = new Payment(); + payment.setIntent("sale"); + ... + payment.create(apiContext); + ``` SDK Configuration: diff --git a/pom.xml b/pom.xml index a3fde597..1e1e08b0 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.paypal.sdk rest-api - 0.5.2 + 0.7.0 pom rest-api diff --git a/rest-api-sample/pom.xml b/rest-api-sample/pom.xml index 4750366e..86766661 100644 --- a/rest-api-sample/pom.xml +++ b/rest-api-sample/pom.xml @@ -3,14 +3,14 @@ 4.0.0 com.paypal.sdk rest-api-sample - 0.5.2 + 0.7.0 REST API SAMPLE war com.paypal.sdk rest-api-sdk - 0.5.2 + 0.7.0 log4j @@ -20,6 +20,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.0 + + 1.5 + 1.5 + + org.mortbay.jetty maven-jetty-plugin diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/AuthorizationCaptureServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/AuthorizationCaptureServlet.java new file mode 100644 index 00000000..80396f9b --- /dev/null +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/AuthorizationCaptureServlet.java @@ -0,0 +1,222 @@ +// #AuthorizationCapture Sample +// This sample code demonstrate how you +// do a Capture on an Authorization +// API used: /v1/payments/authorization/{authorization_id}/capture +package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class AuthorizationCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(AuthorizationCaptureServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException { + // ##Load Configuration + // Load SDK configuration for + // the resource. This intialization code can be + // done as Init Servlet. + InputStream is = AuthorizationCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + + // ##AuthorizationCapture + // Sample showing how to do a Capture using Authorization + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // ###AccessToken + // Retrieve the access token from + // OAuthTokenCredential by passing in + // ClientID and ClientSecret + APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken(); + + // ### Api Context + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id + // (that ensures idempotency). The SDK generates + // a request id if you do not pass one explicitly. + apiContext = new APIContext(accessToken); + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally + // a order id. + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */ + + // ###Authorization + // Retrieve a Authorization object + // by making a Payment with intent + // as 'authorize' + Authorization authorization = getAuthorization(apiContext); + + // ###Amount + // Let's you specify a capture amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54"); + + // ###Capture + // A capture transaction + Capture capture = new Capture(); + capture.setAmount(amount); + + // ##IsFinalCapture + // If set to true, all remaining + // funds held by the authorization + // will be released in the funding + // instrument. Default is ‘false’. + capture.setIsFinalCapture(true); + + // Capture by POSTing to + // URI v1/payments/authorization/{authorization_id}/capture + Capture responseCapture = authorization.capture(apiContext, capture); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Capture id = " + responseCapture.getId() + + " and status = " + responseCapture.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.setAttribute("request", Authorization.getLastRequest()); + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException { + + // ###Details + // Let's you specify details of a payment amount. + Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03"); + + // ###Amount + // Let's you specify a payment amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details); + + // ###Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + + // The Payment creation API requires a list of + // Transaction; add the created `Transaction` + // to a List + List transactions = new ArrayList(); + transactions.add(transaction); + + // ###Address + // Base Address object used as shipping or billing + // address in a payment. [Optional] + Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH"); + + // ###CreditCard + // A resource representing a credit card that can be + // used to fund a payment. + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + // ###FundingInstrument + // A resource representing a Payeer's funding instrument. + // Use a Payer ID (A unique identifier of the payer generated + // and provided by the facilitator. This is required when + // creating or using a tokenized funding instrument) + // and the `CreditCardDetails` + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + + // The Payment creation API requires a list of + // FundingInstrument; add the created `FundingInstrument` + // to a List + List fundingInstruments = new ArrayList(); + fundingInstruments.add(fundingInstrument); + + // ###Payer + // A resource representing a Payer that funds a payment + // Use the List of `FundingInstrument` and the Payment Method + // as 'credit_card' + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card"); + + // ###Payment + // A Payment Resource; create one using + // the above types and intent as 'authorize' + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization(); + } + +} diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/CreateCreditCardServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/CreateCreditCardServlet.java index 0da959b3..8027586e 100644 --- a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/CreateCreditCardServlet.java +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/CreateCreditCardServlet.java @@ -63,8 +63,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) // A resource representing a credit card that can be // used to fund a payment. CreditCard creditCard = new CreditCard(); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setNumber("4417119669820331"); creditCard.setType("visa"); diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetAuthorizationServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetAuthorizationServlet.java new file mode 100644 index 00000000..a9a05a5d --- /dev/null +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetAuthorizationServlet.java @@ -0,0 +1,210 @@ +// #GetAuthorization Sample +// This sample code demonstrate how you +// can retrieve the details of a Authorization +// resource +// API used: /v1/payments/authorization/{id} +package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class GetAuthorizationServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException { + // ##Load Configuration + // Load SDK configuration for + // the resource. This intialization code can be + // done as Init Servlet. + InputStream is = GetAuthorizationServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + + // ##GetAuthorization + // Sample showing how to do a Get Authorization + // using Authorization Id + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // ###AccessToken + // Retrieve the access token from + // OAuthTokenCredential by passing in + // ClientID and ClientSecret + APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken(); + + // ### Api Context + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id + // (that ensures idempotency). The SDK generates + // a request id if you do not pass one explicitly. + apiContext = new APIContext(accessToken); + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally + // a order id. + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */ + + // ###Authorization + // Retrieve an Authorization Id + // by making a Payment with intent + // as 'authorize' and parsing through + // the Payment object + String authorizationId = getAuthorizationID(apiContext); + + // Get Authorization by sending + // a GET request with authorization Id + // to the + // URI v1/payments/authorization/{id} + Authorization authorization = Authorization.get(apiContext, + authorizationId); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Authorization id = " + authorization.getId() + + " and status = " + authorization.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private String getAuthorizationID(APIContext apiContext) + throws PayPalRESTException { + String authorizationID = null; + + // ###Details + // Let's you specify details of a payment amount. + Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03"); + + // ###Amount + // Let's you specify a payment amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details); + + // ###Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + + // The Payment creation API requires a list of + // Transaction; add the created `Transaction` + // to a List + List transactions = new ArrayList(); + transactions.add(transaction); + + // ###Address + // Base Address object used as shipping or billing + // address in a payment. [Optional] + Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH"); + + // ###CreditCard + // A resource representing a credit card that can be + // used to fund a payment. + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + // ###FundingInstrument + // A resource representing a Payeer's funding instrument. + // Use a Payer ID (A unique identifier of the payer generated + // and provided by the facilitator. This is required when + // creating or using a tokenized funding instrument) + // and the `CreditCardDetails` + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + + // The Payment creation API requires a list of + // FundingInstrument; add the created `FundingInstrument` + // to a List + List fundingInstruments = new ArrayList(); + fundingInstruments.add(fundingInstrument); + + // ###Payer + // A resource representing a Payer that funds a payment + // Use the List of `FundingInstrument` and the Payment Method + // as 'credit_card' + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card"); + + // ###Payment + // A Payment Resource; create one using + // the above types and intent as 'authorize' + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + + // Retrieve the authorization Id + authorizationID = responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId(); + return authorizationID; + } + +} diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetCaptureServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetCaptureServlet.java new file mode 100644 index 00000000..b1b652e8 --- /dev/null +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetCaptureServlet.java @@ -0,0 +1,239 @@ +// #GetCapture Sample +// This sample code demonstrate how you +// can retrieve the details of a Capture +// resource +// API used: /v1/payments/capture/{capture_id} +package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class GetCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException { + // ##Load Configuration + // Load SDK configuration for + // the resource. This intialization code can be + // done as Init Servlet. + InputStream is = GetCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + + // ##GetCapture + // Sample showing how to Get a Capture using + // CaptureId + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // ###AccessToken + // Retrieve the access token from + // OAuthTokenCredential by passing in + // ClientID and ClientSecret + APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken(); + + // ### Api Context + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id + // (that ensures idempotency). The SDK generates + // a request id if you do not pass one explicitly. + apiContext = new APIContext(accessToken); + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally + // a order id. + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */ + + // ###Authorization + // Retrieve a Authorization object + // by making a Payment with intent + // as 'authorize' + Authorization authorization = getAuthorization(apiContext); + + /// ###Capture + // Create a Capture object + // by doing a capture on + // Authorization object + // and retrieve the Id + String captureId = getCaptureId(apiContext, authorization); + + // Retrieve the Capture object by + // doing a GET call to + // URI v1/payments/capture/{capture_id} + Capture capture = Capture.get(apiContext, captureId); + + req.setAttribute("response", Capture.getLastResponse()); + LOGGER.info("Capture id = " + capture.getId() + + " and status = " + capture.getState()); + + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private String getCaptureId(APIContext apiContext, Authorization authorization) throws PayPalRESTException{ + String captureId = null; + + // ###Amount + // Let's you specify a capture amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54"); + + // ###Capture + Capture capture = new Capture(); + capture.setAmount(amount); + + // ##IsFinalCapture + // If set to true, all remaining + // funds held by the authorization + // will be released in the funding + // instrument. Default is ‘false’. + capture.setIsFinalCapture(true); + + // Capture by POSTing to + // URI v1/payments/authorization/{authorization_id}/capture + Capture responseCapture = authorization.capture(apiContext, capture); + captureId = responseCapture.getId(); + + return captureId; + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException { + + // ###Details + // Let's you specify details of a payment amount. + Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03"); + + // ###Amount + // Let's you specify a payment amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details); + + // ###Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + + // The Payment creation API requires a list of + // Transaction; add the created `Transaction` + // to a List + List transactions = new ArrayList(); + transactions.add(transaction); + + // ###Address + // Base Address object used as shipping or billing + // address in a payment. [Optional] + Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH"); + + // ###CreditCard + // A resource representing a credit card that can be + // used to fund a payment. + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + // ###FundingInstrument + // A resource representing a Payeer's funding instrument. + // Use a Payer ID (A unique identifier of the payer generated + // and provided by the facilitator. This is required when + // creating or using a tokenized funding instrument) + // and the `CreditCardDetails` + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + + // The Payment creation API requires a list of + // FundingInstrument; add the created `FundingInstrument` + // to a List + List fundingInstruments = new ArrayList(); + fundingInstruments.add(fundingInstrument); + + // ###Payer + // A resource representing a Payer that funds a payment + // Use the List of `FundingInstrument` and the Payment Method + // as 'credit_card' + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card"); + + // ###Payment + // A Payment Resource; create one using + // the above types and intent as 'authorize' + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0).getRelatedResources() + .get(0).getAuthorization(); + } +} diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentServlet.java index 982533f7..c274274e 100644 --- a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentServlet.java +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/GetPaymentServlet.java @@ -53,7 +53,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) } - // ##GetPaymentByPaymentId + // ##GetPayment // Call the method with a valid Payment ID @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithCreditCardServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithCreditCardServlet.java index 63d9e1c3..464ad5b2 100644 --- a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithCreditCardServlet.java +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithCreditCardServlet.java @@ -71,19 +71,19 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) CreditCard creditCard = new CreditCard(); creditCard.setBillingAddress(billingAddress); creditCard.setCvv2("874"); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setFirstName("Joe"); creditCard.setLastName("Shopper"); creditCard.setNumber("4417119669820331"); creditCard.setType("visa"); - // ###AmountDetails + // ###Details // Let's you specify details of a payment amount. - AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1"); + Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1"); // ###Amount // Let's you specify a payment amount. @@ -91,7 +91,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) amount.setCurrency("USD"); // Total must be equal to sum of shipping, tax and subtotal. amount.setTotal("7"); - amount.setDetails(amountDetails); + amount.setDetails(details); // ###Transaction // A transaction defines the contract of a diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithPayPalServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithPayPalServlet.java index 839a0abf..5f3ebcc7 100644 --- a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithPayPalServlet.java +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithPayPalServlet.java @@ -6,16 +6,33 @@ import java.io.IOException; import java.io.InputStream; -import java.util.*; - -import javax.servlet.*; -import javax.servlet.http.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; -import com.paypal.api.payments.*; -import com.paypal.api.payments.util.*; -import com.paypal.core.rest.*; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.Links; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.PaymentExecution; +import com.paypal.api.payments.RedirectUrls; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; /** * @author lvairamani @@ -65,17 +82,17 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) accessToken = GenerateAccessToken.getAccessToken(); // ### Api Context - // Pass in a `ApiContext` object to authenticate - // the call and to send a unique request id + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id // (that ensures idempotency). The SDK generates - // a request id if you do not pass one explicitly. + // a request id if you do not pass one explicitly. apiContext = new APIContext(accessToken); - // Use this variant if you want to pass in a request id - // that is meaningful in your application, ideally + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally // a order id. - /* - * String requestId = Long.toString(System.nanoTime(); - * APIContext apiContext = new APIContext(accessToken, requestId )); + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); */ } catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); @@ -96,12 +113,12 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) } } else { - // ###AmountDetails + // ###Details // Let's you specify details of a payment amount. - AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1"); + Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1"); // ###Amount // Let's you specify a payment amount. @@ -109,7 +126,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) amount.setCurrency("USD"); // Total must be equal to sum of shipping, tax and subtotal. amount.setTotal("7"); - amount.setDetails(amountDetails); + amount.setDetails(details); // ###Transaction // A transaction defines the contract of a @@ -162,9 +179,9 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) + createdPayment.getId() + " and status = " + createdPayment.getState()); // ###Payment Approval Url - Iterator links = createdPayment.getLinks().iterator(); + Iterator links = createdPayment.getLinks().iterator(); while (links.hasNext()) { - Link link = links.next(); + Links link = links.next(); if (link.getRel().equalsIgnoreCase("approval_url")) { req.setAttribute("redirectURL", link.getHref()); } diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithSavedCardServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithSavedCardServlet.java index 10b0f7b6..b066d4cb 100644 --- a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithSavedCardServlet.java +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithSavedCardServlet.java @@ -63,12 +63,12 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) CreditCardToken creditCardToken = new CreditCardToken(); creditCardToken.setCreditCardId("CARD-5BT058015C739554AKE2GCEI"); - // ###AmountDetails + // ###Details // Let's you specify details of a payment amount. - AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1"); + Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1"); // ###Amount // Let's you specify a payment amount. @@ -76,7 +76,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) amount.setCurrency("USD"); // Total must be equal to the sum of shipping, tax and subtotal. amount.setTotal("7"); - amount.setDetails(amountDetails); + amount.setDetails(details); // ###Transaction // A transaction defines the contract of a diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/RefundCaptureServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/RefundCaptureServlet.java new file mode 100644 index 00000000..23d64c7a --- /dev/null +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/RefundCaptureServlet.java @@ -0,0 +1,250 @@ +// #RefundCapture Sample +// This sample code demonstrate how you +// can do a Refund on a Capture +// resource +// API used: /v1/payments/capture/{capture_id}/refund +package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Refund; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class RefundCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException { + // ##Load Configuration + // Load SDK configuration for + // the resource. This intialization code can be + // done as Init Servlet. + InputStream is = RefundCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + + // ##RefundCapture + // Sample showing to how to do a Refund on + // a Capture + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // ###AccessToken + // Retrieve the access token from + // OAuthTokenCredential by passing in + // ClientID and ClientSecret + APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken(); + + // ### Api Context + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id + // (that ensures idempotency). The SDK generates + // a request id if you do not pass one explicitly. + apiContext = new APIContext(accessToken); + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally + // a order id. + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */ + + // ###Authorization + // Retrieve a Authorization object + // by making a Payment with intent + // as 'authorize' + Authorization authorization = getAuthorization(apiContext); + + /// ###Capture + // Create a Capture object + // by doing a capture on + // Authorization object + Capture capture = getCapture(apiContext, authorization); + + /// ###Refund + /// Create a Refund object + Refund refund = new Refund(); + + // ###Amount + // Let's you specify a capture amount. + Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + + refund.setAmount(amount); + + // Create new APIContext for + // Refund + apiContext = new APIContext(accessToken); + // Do a Refund by + // POSTing to + // URI v1/payments/capture/{capture_id}/refund + Refund responseRefund = capture.refund(apiContext, refund); + + req.setAttribute("response", Capture.getLastResponse()); + LOGGER.info("Refund id = " + responseRefund.getId() + + " and status = " + responseRefund.getState()); + + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.setAttribute("request", Capture.getLastRequest()); + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Capture getCapture(APIContext apiContext, Authorization authorization) throws PayPalRESTException{ + // ###Amount + // Let's you specify a capture amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54"); + + // ###Capture + Capture capture = new Capture(); + capture.setAmount(amount); + + // ##IsFinalCapture + // If set to true, all remaining + // funds held by the authorization + // will be released in the funding + // instrument. Default is ‘false’. + capture.setIsFinalCapture(true); + + // Capture by POSTing to + // URI v1/payments/authorization/{authorization_id}/capture + Capture responseCapture = authorization.capture(apiContext, capture); + return responseCapture; + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException { + + // ###Details + // Let's you specify details of a payment amount. + Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03"); + + // ###Amount + // Let's you specify a payment amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details); + + // ###Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + + // The Payment creation API requires a list of + // Transaction; add the created `Transaction` + // to a List + List transactions = new ArrayList(); + transactions.add(transaction); + + // ###Address + // Base Address object used as shipping or billing + // address in a payment. [Optional] + Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH"); + + // ###CreditCard + // A resource representing a credit card that can be + // used to fund a payment. + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + // ###FundingInstrument + // A resource representing a Payeer's funding instrument. + // Use a Payer ID (A unique identifier of the payer generated + // and provided by the facilitator. This is required when + // creating or using a tokenized funding instrument) + // and the `CreditCardDetails` + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + + // The Payment creation API requires a list of + // FundingInstrument; add the created `FundingInstrument` + // to a List + List fundingInstruments = new ArrayList(); + fundingInstruments.add(fundingInstrument); + + // ###Payer + // A resource representing a Payer that funds a payment + // Use the List of `FundingInstrument` and the Payment Method + // as 'credit_card' + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card"); + + // ###Payment + // A Payment Resource; create one using + // the above types and intent as 'authorize' + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0).getRelatedResources() + .get(0).getAuthorization(); + } +} diff --git a/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/VoidAuthorizationServlet.java b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/VoidAuthorizationServlet.java new file mode 100644 index 00000000..55670b37 --- /dev/null +++ b/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/VoidAuthorizationServlet.java @@ -0,0 +1,205 @@ +// #VoidAuthorization Sample +// This sample code demonstrate how you +// can do a Void on a Authorization +// resource +// API used: /v1/payments/authorization/{authorization_id}/void +package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class VoidAuthorizationServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(VoidAuthorizationServlet.class); + Map map = new HashMap(); + + public void init(ServletConfig servletConfig) throws ServletException { + // ##Load Configuration + // Load SDK configuration for + // the resource. This intialization code can be + // done as Init Servlet. + InputStream is = VoidAuthorizationServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + + // ##VoidAuthorization + // Sample showing how to void an Authorization + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // ###AccessToken + // Retrieve the access token from + // OAuthTokenCredential by passing in + // ClientID and ClientSecret + APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken(); + + // ### Api Context + // Pass in a `ApiContext` object to authenticate + // the call and to send a unique request id + // (that ensures idempotency). The SDK generates + // a request id if you do not pass one explicitly. + apiContext = new APIContext(accessToken); + // Use this variant if you want to pass in a request id + // that is meaningful in your application, ideally + // a order id. + /* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */ + + // ###Authorization + // Retrieve a Authorization object + // by making a Payment with intent + // as 'authorize' + Authorization authorization = getAuthorization(apiContext); + + // Void an Authorization + // by POSTing to + // URI v1/payments/authorization/{authorization_id}/void + Authorization returnAuthorization = authorization.doVoid(apiContext); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Authorization id = " + returnAuthorization.getId() + + " and status = " + returnAuthorization.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException { + + // ###Details + // Let's you specify details of a payment amount. + Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03"); + + // ###Amount + // Let's you specify a payment amount. + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details); + + // ###Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + + // The Payment creation API requires a list of + // Transaction; add the created `Transaction` + // to a List + List transactions = new ArrayList(); + transactions.add(transaction); + + // ###Address + // Base Address object used as shipping or billing + // address in a payment. [Optional] + Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH"); + + // ###CreditCard + // A resource representing a credit card that can be + // used to fund a payment. + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + // ###FundingInstrument + // A resource representing a Payeer's funding instrument. + // Use a Payer ID (A unique identifier of the payer generated + // and provided by the facilitator. This is required when + // creating or using a tokenized funding instrument) + // and the `CreditCardDetails` + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + + // The Payment creation API requires a list of + // FundingInstrument; add the created `FundingInstrument` + // to a List + List fundingInstruments = new ArrayList(); + fundingInstruments.add(fundingInstrument); + + // ###Payer + // A resource representing a Payer that funds a payment + // Use the List of `FundingInstrument` and the Payment Method + // as 'credit_card' + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card"); + + // ###Payment + // A Payment Resource; create one using + // the above types and intent as 'authorize' + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization(); + } + +} diff --git a/rest-api-sample/src/main/webapp/WEB-INF/web.xml b/rest-api-sample/src/main/webapp/WEB-INF/web.xml index 9d3900f3..629e9c56 100644 --- a/rest-api-sample/src/main/webapp/WEB-INF/web.xml +++ b/rest-api-sample/src/main/webapp/WEB-INF/web.xml @@ -1,85 +1,126 @@ - - OAuth2TokenGenerator - - - 30 - - - - index.html - - - PaymentWithCreditCardServlet - com.paypal.api.payments.servlet.PaymentWithCreditCardServlet - - - PaymentWithCreditCardServlet - /paymentwithcreditcard - - - PaymentWithPayPalServlet - com.paypal.api.payments.servlet.PaymentWithPayPalServlet - - - PaymentWithPayPalServlet - /paymentwithpaypal - - - PaymentWithSavedCardServlet - com.paypal.api.payments.servlet.PaymentWithSavedCardServlet - - - PaymentWithSavedCardServlet - /paymentwithsavedcard - - - GetPaymentServlet - com.paypal.api.payments.servlet.GetPaymentServlet - - - GetPaymentServlet - /getpayment - - - GetPaymentHistoryServlet - com.paypal.api.payments.servlet.GetPaymentHistoryServlet - - - GetPaymentHistoryServlet - /getpaymenthistory - - - GetSaleServlet - com.paypal.api.payments.servlet.GetSaleServlet - - - GetSaleServlet - /getsale - - - SaleRefundServlet - com.paypal.api.payments.servlet.SaleRefundServlet - - - SaleRefundServlet - /salerefund - - - CreateCreditCardServlet - com.paypal.api.payments.servlet.CreateCreditCardServlet - - - CreateCreditCardServlet - /createcreditcard - - - GetCreditCardServlet - com.paypal.api.payments.servlet.GetCreditCardServlet - - - GetCreditCardServlet - /getcreditcard - - - + + OAuth2TokenGenerator + + 30 + + + index.html + + + GetAuthorizationServlet + com.paypal.api.payments.servlet.GetAuthorizationServlet + + + AuthorizationCaptureServlet + com.paypal.api.payments.servlet.AuthorizationCaptureServlet + + + VoidAuthorizationServlet + com.paypal.api.payments.servlet.VoidAuthorizationServlet + + + GetCaptureServlet + com.paypal.api.payments.servlet.GetCaptureServlet + + + RefundCaptureServlet + com.paypal.api.payments.servlet.RefundCaptureServlet + + + PaymentWithCreditCardServlet + com.paypal.api.payments.servlet.PaymentWithCreditCardServlet + + + PaymentWithCreditCardServlet + /paymentwithcreditcard + + + PaymentWithPayPalServlet + com.paypal.api.payments.servlet.PaymentWithPayPalServlet + + + PaymentWithPayPalServlet + /paymentwithpaypal + + + PaymentWithSavedCardServlet + com.paypal.api.payments.servlet.PaymentWithSavedCardServlet + + + + GetAuthorizationServlet + /getauthorizationservlet + + + AuthorizationCaptureServlet + /authorizationcaptureservlet + + + VoidAuthorizationServlet + /voidauthorizationservlet + + + GetCaptureServlet + /getcaptureservlet + + + RefundCaptureServlet + /refundcaptureservlet + + + PaymentWithSavedCardServlet + /paymentwithsavedcard + + + GetPaymentServlet + com.paypal.api.payments.servlet.GetPaymentServlet + + + GetPaymentServlet + /getpayment + + + GetPaymentHistoryServlet + com.paypal.api.payments.servlet.GetPaymentHistoryServlet + + + GetPaymentHistoryServlet + /getpaymenthistory + + + GetSaleServlet + com.paypal.api.payments.servlet.GetSaleServlet + + + GetSaleServlet + /getsale + + + SaleRefundServlet + com.paypal.api.payments.servlet.SaleRefundServlet + + + SaleRefundServlet + /salerefund + + + CreateCreditCardServlet + com.paypal.api.payments.servlet.CreateCreditCardServlet + + + CreateCreditCardServlet + /createcreditcard + + + GetCreditCardServlet + com.paypal.api.payments.servlet.GetCreditCardServlet + + + GetCreditCardServlet + /getcreditcard + + + diff --git a/rest-api-sample/src/main/webapp/index.html b/rest-api-sample/src/main/webapp/index.html index a6404061..a574677c 100644 --- a/rest-api-sample/src/main/webapp/index.html +++ b/rest-api-sample/src/main/webapp/index.html @@ -114,6 +114,58 @@

PayPal REST API Samples

Source + + + + Get Authorization + + Execute + + Source + + + Capture Authorization + + Execute + + Source + + + Void Authorization + + Execute + + Source + + + Get Capture + + Execute + + Source + + + Refund Capture + + Execute + + Source + diff --git a/rest-api-sample/src/main/webapp/source/AuthorizationCaptureServlet.html b/rest-api-sample/src/main/webapp/source/AuthorizationCaptureServlet.html new file mode 100644 index 00000000..21ef0bab --- /dev/null +++ b/rest-api-sample/src/main/webapp/source/AuthorizationCaptureServlet.html @@ -0,0 +1,186 @@ +AuthorizationCaptureServletBack

AuthorizationCapture Sample

+ +

This sample code demonstrate how you +do a Capture on an Authorization +API used: /v1/payments/authorization/{authorization_id}/capture

package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class AuthorizationCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(AuthorizationCaptureServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException {

Load Configuration

+ +

Load SDK configuration for +the resource. This intialization code can be +done as Init Servlet.

InputStream is = AuthorizationCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + }

AuthorizationCapture

+ +

Sample showing how to do a Capture using Authorization

@Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException {

AccessToken

+ +

Retrieve the access token from +OAuthTokenCredential by passing in +ClientID and ClientSecret

APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken();

Api Context

+ +

Pass in a ApiContext object to authenticate +the call and to send a unique request id +(that ensures idempotency). The SDK generates +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */

Authorization

+ +

Retrieve a Authorization object +by making a Payment with intent +as 'authorize'

Authorization authorization = getAuthorization(apiContext);

Amount

+ +

Let's you specify a capture amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54");

Capture

+ +

A capture transaction

Capture capture = new Capture(); + capture.setAmount(amount); +

IsFinalCapture

+ +

If set to true, all remaining +funds held by the authorization +will be released in the funding +instrument. Default is �false�.

capture.setIsFinalCapture(true);

Capture by POSTing to +URI v1/payments/authorization/{authorization_id}/capture

Capture responseCapture = authorization.capture(apiContext, capture); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Capture id = " + responseCapture.getId() + + " and status = " + responseCapture.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.setAttribute("request", Authorization.getLastRequest()); + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException {

Details

+ +

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03");

Amount

+ +

Let's you specify a payment amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details);

Transaction

+ +

A transaction defines the contract of a +payment - what is the payment for and who +is fulfilling it. Transaction is created with +a Payee and Amount types

Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); +

The Payment creation API requires a list of +Transaction; add the created Transaction +to a List

List<Transaction> transactions = new ArrayList<Transaction>(); + transactions.add(transaction);

Address

+ +

Base Address object used as shipping or billing +address in a payment. [Optional]

Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH");

CreditCard

+ +

A resource representing a credit card that can be +used to fund a payment.

CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); +

FundingInstrument

+ +

A resource representing a Payeer's funding instrument. +Use a Payer ID (A unique identifier of the payer generated +and provided by the facilitator. This is required when +creating or using a tokenized funding instrument) +and the CreditCardDetails

FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); +

The Payment creation API requires a list of +FundingInstrument; add the created FundingInstrument +to a List

List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>(); + fundingInstruments.add(fundingInstrument); +

Payer

+ +

A resource representing a Payer that funds a payment +Use the List of FundingInstrument and the Payment Method +as 'credit_card'

Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card");

Payment

+ +

A Payment Resource; create one using +the above types and intent as 'authorize'

Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization(); + } + +}
\ No newline at end of file diff --git a/rest-api-sample/src/main/webapp/source/CreateCreditCardServlet.html b/rest-api-sample/src/main/webapp/source/CreateCreditCardServlet.html index e3c96d5c..afb47f0c 100644 --- a/rest-api-sample/src/main/webapp/source/CreateCreditCardServlet.html +++ b/rest-api-sample/src/main/webapp/source/CreateCreditCardServlet.html @@ -59,8 +59,8 @@

A resource representing a credit card that can be used to fund a payment.

CreditCard creditCard = new CreditCard(); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setNumber("4417119669820331"); creditCard.setType("visa"); diff --git a/rest-api-sample/src/main/webapp/source/GetAuthorizationServlet.html b/rest-api-sample/src/main/webapp/source/GetAuthorizationServlet.html new file mode 100644 index 00000000..1aa52bd6 --- /dev/null +++ b/rest-api-sample/src/main/webapp/source/GetAuthorizationServlet.html @@ -0,0 +1,172 @@ +GetAuthorizationServletBack

GetAuthorization Sample

+ +

This sample code demonstrate how you +can retrieve the details of a Authorization +resource +API used: /v1/payments/authorization/{id}

package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class GetAuthorizationServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException {

Load Configuration

+ +

Load SDK configuration for +the resource. This intialization code can be +done as Init Servlet.

InputStream is = GetAuthorizationServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + }

GetAuthorization

+ +

Sample showing how to do a Get Authorization +using Authorization Id

@Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException {

AccessToken

+ +

Retrieve the access token from +OAuthTokenCredential by passing in +ClientID and ClientSecret

APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken();

Api Context

+ +

Pass in a ApiContext object to authenticate +the call and to send a unique request id +(that ensures idempotency). The SDK generates +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */

Authorization

+ +

Retrieve an Authorization Id +by making a Payment with intent +as 'authorize' and parsing through +the Payment object

String authorizationId = getAuthorizationID(apiContext);

Get Authorization by sending +a GET request with authorization Id +to the +URI v1/payments/authorization/{id}

Authorization authorization = Authorization.get(apiContext, + authorizationId); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Authorization id = " + authorization.getId() + + " and status = " + authorization.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private String getAuthorizationID(APIContext apiContext) + throws PayPalRESTException { + String authorizationID = null;

Details

+ +

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03");

Amount

+ +

Let's you specify a payment amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details);

Transaction

+ +

A transaction defines the contract of a +payment - what is the payment for and who +is fulfilling it. Transaction is created with +a Payee and Amount types

Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description.");

The Payment creation API requires a list of +Transaction; add the created Transaction +to a List

List<Transaction> transactions = new ArrayList<Transaction>(); + transactions.add(transaction);

Address

+ +

Base Address object used as shipping or billing +address in a payment. [Optional]

Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH");

CreditCard

+ +

A resource representing a credit card that can be +used to fund a payment.

CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa");

FundingInstrument

+ +

A resource representing a Payeer's funding instrument. +Use a Payer ID (A unique identifier of the payer generated +and provided by the facilitator. This is required when +creating or using a tokenized funding instrument) +and the CreditCardDetails

FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard);

The Payment creation API requires a list of +FundingInstrument; add the created FundingInstrument +to a List

List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>(); + fundingInstruments.add(fundingInstrument);

Payer

+ +

A resource representing a Payer that funds a payment +Use the List of FundingInstrument and the Payment Method +as 'credit_card'

Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card");

Payment

+ +

A Payment Resource; create one using +the above types and intent as 'authorize'

Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext);

Retrieve the authorization Id

authorizationID = responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId(); + return authorizationID; + } + +}
\ No newline at end of file diff --git a/rest-api-sample/src/main/webapp/source/GetCaptureServlet.html b/rest-api-sample/src/main/webapp/source/GetCaptureServlet.html new file mode 100644 index 00000000..77f37540 --- /dev/null +++ b/rest-api-sample/src/main/webapp/source/GetCaptureServlet.html @@ -0,0 +1,196 @@ +GetCaptureServletBack

GetCapture Sample

+ +

This sample code demonstrate how you +can retrieve the details of a Capture +resource +API used: /v1/payments/capture/{capture_id}

package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class GetCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException {

Load Configuration

+ +

Load SDK configuration for +the resource. This intialization code can be +done as Init Servlet.

InputStream is = GetCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } +

GetCapture

+ +

Sample showing how to Get a Capture using +CaptureId

@Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException {

AccessToken

+ +

Retrieve the access token from +OAuthTokenCredential by passing in +ClientID and ClientSecret

APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken();

Api Context

+ +

Pass in a ApiContext object to authenticate +the call and to send a unique request id +(that ensures idempotency). The SDK generates +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */

Authorization

+ +

Retrieve a Authorization object +by making a Payment with intent +as 'authorize'

Authorization authorization = getAuthorization(apiContext); + + /// ###Capture

Create a Capture object +by doing a capture on +Authorization object +and retrieve the Id

String captureId = getCaptureId(apiContext, authorization); +

Retrieve the Capture object by +doing a GET call to +URI v1/payments/capture/{capture_id}

Capture capture = Capture.get(apiContext, captureId); + + req.setAttribute("response", Capture.getLastResponse()); + LOGGER.info("Capture id = " + capture.getId() + + " and status = " + capture.getState()); + + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private String getCaptureId(APIContext apiContext, Authorization authorization) throws PayPalRESTException{ + String captureId = null; +

Amount

+ +

Let's you specify a capture amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54");

Capture

Capture capture = new Capture(); + capture.setAmount(amount); +

IsFinalCapture

+ +

If set to true, all remaining +funds held by the authorization +will be released in the funding +instrument. Default is �false�.

capture.setIsFinalCapture(true);

Capture by POSTing to +URI v1/payments/authorization/{authorization_id}/capture

Capture responseCapture = authorization.capture(apiContext, capture); + captureId = responseCapture.getId(); + + return captureId; + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException {

Details

+ +

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03");

Amount

+ +

Let's you specify a payment amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details);

Transaction

+ +

A transaction defines the contract of a +payment - what is the payment for and who +is fulfilling it. Transaction is created with +a Payee and Amount types

Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description.");

The Payment creation API requires a list of +Transaction; add the created Transaction +to a List

List<Transaction> transactions = new ArrayList<Transaction>(); + transactions.add(transaction);

Address

+ +

Base Address object used as shipping or billing +address in a payment. [Optional]

Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH");

CreditCard

+ +

A resource representing a credit card that can be +used to fund a payment.

CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa");

FundingInstrument

+ +

A resource representing a Payeer's funding instrument. +Use a Payer ID (A unique identifier of the payer generated +and provided by the facilitator. This is required when +creating or using a tokenized funding instrument) +and the CreditCardDetails

FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard);

The Payment creation API requires a list of +FundingInstrument; add the created FundingInstrument +to a List

List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>(); + fundingInstruments.add(fundingInstrument);

Payer

+ +

A resource representing a Payer that funds a payment +Use the List of FundingInstrument and the Payment Method +as 'credit_card'

Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card");

Payment

+ +

A Payment Resource; create one using +the above types and intent as 'authorize'

Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0).getRelatedResources() + .get(0).getAuthorization(); + } +}
\ No newline at end of file diff --git a/rest-api-sample/src/main/webapp/source/GetPaymentServlet.html b/rest-api-sample/src/main/webapp/source/GetPaymentServlet.html index 05984cc5..89bf9b33 100644 --- a/rest-api-sample/src/main/webapp/source/GetPaymentServlet.html +++ b/rest-api-sample/src/main/webapp/source/GetPaymentServlet.html @@ -50,7 +50,7 @@ throws ServletException, IOException { doPost(req, resp); - }

GetPaymentByPaymentId

+ }

GetPayment

Call the method with a valid Payment ID

@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) diff --git a/rest-api-sample/src/main/webapp/source/PaymentWithCreditCardServlet.html b/rest-api-sample/src/main/webapp/source/PaymentWithCreditCardServlet.html index 66626a44..62085834 100644 --- a/rest-api-sample/src/main/webapp/source/PaymentWithCreditCardServlet.html +++ b/rest-api-sample/src/main/webapp/source/PaymentWithCreditCardServlet.html @@ -64,21 +64,21 @@ used to fund a payment.

CreditCard creditCard = new CreditCard(); creditCard.setBillingAddress(billingAddress); creditCard.setCvv2("874"); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setFirstName("Joe"); creditCard.setLastName("Shopper"); creditCard.setNumber("4417119669820331"); - creditCard.setType("visa");

AmountDetails

+ creditCard.setType("visa");

Details

-

Let's you specify details of a payment amount.

AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1");

Amount

+

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1");

Amount

Let's you specify a payment amount.

Amount amount = new Amount(); amount.setCurrency("USD");

Total must be equal to sum of shipping, tax and subtotal.

amount.setTotal("7"); - amount.setDetails(amountDetails);

Transaction

+ amount.setDetails(details);

Transaction

A transaction defines the contract of a payment - what is the payment for and who diff --git a/rest-api-sample/src/main/webapp/source/PaymentWithPayPalServlet.html b/rest-api-sample/src/main/webapp/source/PaymentWithPayPalServlet.html index c45e9725..8b428a7a 100644 --- a/rest-api-sample/src/main/webapp/source/PaymentWithPayPalServlet.html +++ b/rest-api-sample/src/main/webapp/source/PaymentWithPayPalServlet.html @@ -6,16 +6,33 @@ import java.io.IOException; import java.io.InputStream; -import java.util.*; - -import javax.servlet.*; -import javax.servlet.http.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; -import com.paypal.api.payments.*; -import com.paypal.api.payments.util.*; -import com.paypal.core.rest.*; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.Links; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.PaymentExecution; +import com.paypal.api.payments.RedirectUrls; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; /** * @author lvairamani @@ -60,14 +77,14 @@ try { accessToken = GenerateAccessToken.getAccessToken();

Api Context

-

Pass in a ApiContext object to authenticate -the call and to send a unique request id +

Pass in a ApiContext object to authenticate +the call and to send a unique request id (that ensures idempotency). The SDK generates -a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id
-that is meaningful in your application, ideally -a order id.

/* - * String requestId = Long.toString(System.nanoTime(); - * APIContext apiContext = new APIContext(accessToken, requestId )); +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); */ } catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); @@ -86,16 +103,16 @@ } catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); } - } else {

AmountDetails

+ } else {

Details

-

Let's you specify details of a payment amount.

AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1");

Amount

+

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1");

Amount

Let's you specify a payment amount.

Amount amount = new Amount(); amount.setCurrency("USD");

Total must be equal to sum of shipping, tax and subtotal.

amount.setTotal("7"); - amount.setDetails(amountDetails);

Transaction

+ amount.setDetails(details);

Transaction

A transaction defines the contract of a payment - what is the payment for and who @@ -131,9 +148,9 @@ Payment createdPayment = payment.create(apiContext); LOGGER.info("Created payment with id = " + createdPayment.getId() + " and status = " - + createdPayment.getState());

Payment Approval Url

Iterator<Link> links = createdPayment.getLinks().iterator(); + + createdPayment.getState());

Payment Approval Url

Iterator<Links> links = createdPayment.getLinks().iterator(); while (links.hasNext()) { - Link link = links.next(); + Links link = links.next(); if (link.getRel().equalsIgnoreCase("approval_url")) { req.setAttribute("redirectURL", link.getHref()); } diff --git a/rest-api-sample/src/main/webapp/source/PaymentWithSavedCardServlet.html b/rest-api-sample/src/main/webapp/source/PaymentWithSavedCardServlet.html index 32dd0882..484680ee 100644 --- a/rest-api-sample/src/main/webapp/source/PaymentWithSavedCardServlet.html +++ b/rest-api-sample/src/main/webapp/source/PaymentWithSavedCardServlet.html @@ -56,16 +56,16 @@

A resource representing a credit card that can be used to fund a payment.

CreditCardToken creditCardToken = new CreditCardToken(); - creditCardToken.setCreditCardId("CARD-5BT058015C739554AKE2GCEI");

AmountDetails

+ creditCardToken.setCreditCardId("CARD-5BT058015C739554AKE2GCEI");

Details

-

Let's you specify details of a payment amount.

AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("1"); - amountDetails.setSubtotal("5"); - amountDetails.setTax("1");

Amount

+

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("1"); + details.setSubtotal("5"); + details.setTax("1");

Amount

Let's you specify a payment amount.

Amount amount = new Amount(); amount.setCurrency("USD");

Total must be equal to the sum of shipping, tax and subtotal.

amount.setTotal("7"); - amount.setDetails(amountDetails);

Transaction

+ amount.setDetails(details);

Transaction

A transaction defines the contract of a payment - what is the payment for and who diff --git a/rest-api-sample/src/main/webapp/source/RefundCaptureServlet.html b/rest-api-sample/src/main/webapp/source/RefundCaptureServlet.html new file mode 100644 index 00000000..624d1b1d --- /dev/null +++ b/rest-api-sample/src/main/webapp/source/RefundCaptureServlet.html @@ -0,0 +1,204 @@ +RefundCaptureServletBack

RefundCapture Sample

+ +

This sample code demonstrate how you +can do a Refund on a Capture +resource +API used: /v1/payments/capture/{capture_id}/refund

package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.Capture; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Refund; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class RefundCaptureServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(GetAuthorizationServlet.class); + + public void init(ServletConfig servletConfig) throws ServletException {

Load Configuration

+ +

Load SDK configuration for +the resource. This intialization code can be +done as Init Servlet.

InputStream is = RefundCaptureServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } +

RefundCapture

+ +

Sample showing to how to do a Refund on +a Capture

@Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException {

AccessToken

+ +

Retrieve the access token from +OAuthTokenCredential by passing in +ClientID and ClientSecret

APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken();

Api Context

+ +

Pass in a ApiContext object to authenticate +the call and to send a unique request id +(that ensures idempotency). The SDK generates +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */

Authorization

+ +

Retrieve a Authorization object +by making a Payment with intent +as 'authorize'

Authorization authorization = getAuthorization(apiContext); + + /// ###Capture

Create a Capture object +by doing a capture on +Authorization object

Capture capture = getCapture(apiContext, authorization); + + /// ###Refund + /// Create a Refund object + Refund refund = new Refund(); +

Amount

+ +

Let's you specify a capture amount.

Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + + refund.setAmount(amount); +

Create new APIContext for +Refund

apiContext = new APIContext(accessToken);

Do a Refund by +POSTing to +URI v1/payments/capture/{capture_id}/refund

Refund responseRefund = capture.refund(apiContext, refund); + + req.setAttribute("response", Capture.getLastResponse()); + LOGGER.info("Refund id = " + responseRefund.getId() + + " and status = " + responseRefund.getState()); + + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.setAttribute("request", Capture.getLastRequest()); + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Capture getCapture(APIContext apiContext, Authorization authorization) throws PayPalRESTException{

Amount

+ +

Let's you specify a capture amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("4.54");

Capture

Capture capture = new Capture(); + capture.setAmount(amount); +

IsFinalCapture

+ +

If set to true, all remaining +funds held by the authorization +will be released in the funding +instrument. Default is �false�.

capture.setIsFinalCapture(true);

Capture by POSTing to +URI v1/payments/authorization/{authorization_id}/capture

Capture responseCapture = authorization.capture(apiContext, capture); + return responseCapture; + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException {

Details

+ +

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03");

Amount

+ +

Let's you specify a payment amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details);

Transaction

+ +

A transaction defines the contract of a +payment - what is the payment for and who +is fulfilling it. Transaction is created with +a Payee and Amount types

Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description.");

The Payment creation API requires a list of +Transaction; add the created Transaction +to a List

List<Transaction> transactions = new ArrayList<Transaction>(); + transactions.add(transaction);

Address

+ +

Base Address object used as shipping or billing +address in a payment. [Optional]

Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH");

CreditCard

+ +

A resource representing a credit card that can be +used to fund a payment.

CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa");

FundingInstrument

+ +

A resource representing a Payeer's funding instrument. +Use a Payer ID (A unique identifier of the payer generated +and provided by the facilitator. This is required when +creating or using a tokenized funding instrument) +and the CreditCardDetails

FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard);

The Payment creation API requires a list of +FundingInstrument; add the created FundingInstrument +to a List

List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>(); + fundingInstruments.add(fundingInstrument);

Payer

+ +

A resource representing a Payer that funds a payment +Use the List of FundingInstrument and the Payment Method +as 'credit_card'

Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card");

Payment

+ +

A Payment Resource; create one using +the above types and intent as 'authorize'

Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0).getRelatedResources() + .get(0).getAuthorization(); + } +}
\ No newline at end of file diff --git a/rest-api-sample/src/main/webapp/source/VoidAuthorizationServlet.html b/rest-api-sample/src/main/webapp/source/VoidAuthorizationServlet.html new file mode 100644 index 00000000..17288666 --- /dev/null +++ b/rest-api-sample/src/main/webapp/source/VoidAuthorizationServlet.html @@ -0,0 +1,175 @@ +VoidAuthorizationServletBack

VoidAuthorization Sample

+ +

This sample code demonstrate how you +can do a Void on a Authorization +resource +API used: /v1/payments/authorization/{authorization_id}/void

package com.paypal.api.payments.servlet; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.log4j.Logger; + +import com.paypal.api.payments.Address; +import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Authorization; +import com.paypal.api.payments.CreditCard; +import com.paypal.api.payments.Details; +import com.paypal.api.payments.FundingInstrument; +import com.paypal.api.payments.Payer; +import com.paypal.api.payments.Payment; +import com.paypal.api.payments.Transaction; +import com.paypal.api.payments.util.GenerateAccessToken; +import com.paypal.core.rest.APIContext; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; + +public class VoidAuthorizationServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Logger LOGGER = Logger + .getLogger(VoidAuthorizationServlet.class); + Map<String, String> map = new HashMap<String, String>(); + + public void init(ServletConfig servletConfig) throws ServletException {

Load Configuration

+ +

Load SDK configuration for +the resource. This intialization code can be +done as Init Servlet.

InputStream is = VoidAuthorizationServlet.class + .getResourceAsStream("/sdk_config.properties"); + try { + PayPalResource.initConfig(is); + } catch (PayPalRESTException e) { + LOGGER.fatal(e.getMessage()); + } + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } +

VoidAuthorization

+ +

Sample showing how to void an Authorization

@Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException {

AccessToken

+ +

Retrieve the access token from +OAuthTokenCredential by passing in +ClientID and ClientSecret

APIContext apiContext = null; + String accessToken = null; + try { + accessToken = GenerateAccessToken.getAccessToken();

Api Context

+ +

Pass in a ApiContext object to authenticate +the call and to send a unique request id +(that ensures idempotency). The SDK generates +a request id if you do not pass one explicitly.

apiContext = new APIContext(accessToken);

Use this variant if you want to pass in a request id +that is meaningful in your application, ideally +a order id.

/* + * String requestId = Long.toString(System.nanoTime(); APIContext + * apiContext = new APIContext(accessToken, requestId )); + */

Authorization

+ +

Retrieve a Authorization object +by making a Payment with intent +as 'authorize'

Authorization authorization = getAuthorization(apiContext);

Void an Authorization +by POSTing to +URI v1/payments/authorization/{authorization_id}/void

Authorization returnAuthorization = authorization.doVoid(apiContext); + + req.setAttribute("response", Authorization.getLastResponse()); + LOGGER.info("Authorization id = " + returnAuthorization.getId() + + " and status = " + returnAuthorization.getState()); + } catch (PayPalRESTException e) { + req.setAttribute("error", e.getMessage()); + } + req.getRequestDispatcher("response.jsp").forward(req, resp); + } + + private Authorization getAuthorization(APIContext apiContext) + throws PayPalRESTException {

Details

+ +

Let's you specify details of a payment amount.

Details details = new Details(); + details.setShipping("0.03"); + details.setSubtotal("107.41"); + details.setTax("0.03");

Amount

+ +

Let's you specify a payment amount.

Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("107.47"); + amount.setDetails(details);

Transaction

+ +

A transaction defines the contract of a +payment - what is the payment for and who +is fulfilling it. Transaction is created with +a Payee and Amount types

Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); +

The Payment creation API requires a list of +Transaction; add the created Transaction +to a List

List<Transaction> transactions = new ArrayList<Transaction>(); + transactions.add(transaction);

Address

+ +

Base Address object used as shipping or billing +address in a payment. [Optional]

Address billingAddress = new Address(); + billingAddress.setCity("Johnstown"); + billingAddress.setCountryCode("US"); + billingAddress.setLine1("52 N Main ST"); + billingAddress.setPostalCode("43210"); + billingAddress.setState("OH");

CreditCard

+ +

A resource representing a credit card that can be +used to fund a payment.

CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); +

FundingInstrument

+ +

A resource representing a Payeer's funding instrument. +Use a Payer ID (A unique identifier of the payer generated +and provided by the facilitator. This is required when +creating or using a tokenized funding instrument) +and the CreditCardDetails

FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); +

The Payment creation API requires a list of +FundingInstrument; add the created FundingInstrument +to a List

List<FundingInstrument> fundingInstruments = new ArrayList<FundingInstrument>(); + fundingInstruments.add(fundingInstrument); +

Payer

+ +

A resource representing a Payer that funds a payment +Use the List of FundingInstrument and the Payment Method +as 'credit_card'

Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstruments); + payer.setPaymentMethod("credit_card");

Payment

+ +

A Payment Resource; create one using +the above types and intent as 'authorize'

Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + + Payment responsePayment = payment.create(apiContext); + return responsePayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization(); + } + +}
\ No newline at end of file diff --git a/rest-api-sample/src/main/webapp/source/assets/behavior.js b/rest-api-sample/src/main/webapp/source/assets/behavior.js index 72a35a89..9f0ab493 100644 --- a/rest-api-sample/src/main/webapp/source/assets/behavior.js +++ b/rest-api-sample/src/main/webapp/source/assets/behavior.js @@ -6,6 +6,158 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 tableOfContents = [ { + "type": "file", + "data": { + "language": { + "nameMatchers": [".java"], + "pygmentsLexer": "java", + "singleLineComment": ["//"], + "name": "Java" + }, + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\AuthorizationCaptureServlet.java", + "projectPath": "AuthorizationCaptureServlet.java", + "targetPath": "AuthorizationCaptureServlet", + "title": "AuthorizationCaptureServlet" + }, + "depth": 1, + "outline": [ + { + "type": "heading", + "data": { + "level": 2, + "title": "Load Configuration", + "slug": "load-configuration" + }, + "depth": 2 + }, { + "type": "heading", + "data": { + "level": 2, + "title": "AuthorizationCapture", + "slug": "authorizationcapture" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Authorization", + "slug": "authorization" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Capture", + "slug": "capture" + }, + "depth": 3 + } + ] + }, { + "type": "heading", + "data": { + "level": 2, + "title": "IsFinalCapture", + "slug": "isfinalcapture" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Transaction", + "slug": "transaction" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Address", + "slug": "address" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "CreditCard", + "slug": "creditcard" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "FundingInstrument", + "slug": "fundinginstrument" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payer", + "slug": "payer" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payment", + "slug": "payment" + }, + "depth": 3 + } + ] + } + ] + }, { "type": "file", "data": { "language": { @@ -74,6 +226,283 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 ] } ] + }, { + "type": "file", + "data": { + "language": { + "nameMatchers": [".java"], + "pygmentsLexer": "java", + "singleLineComment": ["//"], + "name": "Java" + }, + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\GetAuthorizationServlet.java", + "projectPath": "GetAuthorizationServlet.java", + "targetPath": "GetAuthorizationServlet", + "title": "GetAuthorizationServlet" + }, + "depth": 1, + "outline": [ + { + "type": "heading", + "data": { + "level": 2, + "title": "Load Configuration", + "slug": "load-configuration" + }, + "depth": 2 + }, { + "type": "heading", + "data": { + "level": 2, + "title": "GetAuthorization", + "slug": "getauthorization" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Authorization", + "slug": "authorization" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Transaction", + "slug": "transaction" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Address", + "slug": "address" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "CreditCard", + "slug": "creditcard" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "FundingInstrument", + "slug": "fundinginstrument" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payer", + "slug": "payer" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payment", + "slug": "payment" + }, + "depth": 3 + } + ] + } + ] + }, { + "type": "file", + "data": { + "language": { + "nameMatchers": [".java"], + "pygmentsLexer": "java", + "singleLineComment": ["//"], + "name": "Java" + }, + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\GetCaptureServlet.java", + "projectPath": "GetCaptureServlet.java", + "targetPath": "GetCaptureServlet", + "title": "GetCaptureServlet" + }, + "depth": 1, + "outline": [ + { + "type": "heading", + "data": { + "level": 2, + "title": "Load Configuration", + "slug": "load-configuration" + }, + "depth": 2 + }, { + "type": "heading", + "data": { + "level": 2, + "title": "GetCapture", + "slug": "getcapture" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Authorization", + "slug": "authorization" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Capture", + "slug": "capture" + }, + "depth": 3 + } + ] + }, { + "type": "heading", + "data": { + "level": 2, + "title": "IsFinalCapture", + "slug": "isfinalcapture" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Transaction", + "slug": "transaction" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Address", + "slug": "address" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "CreditCard", + "slug": "creditcard" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "FundingInstrument", + "slug": "fundinginstrument" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payer", + "slug": "payer" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payment", + "slug": "payment" + }, + "depth": 3 + } + ] + } + ] }, { "type": "file", "data": { @@ -192,8 +621,8 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 2, - "title": "GetPaymentByPaymentId", - "slug": "getpaymentbypaymentid" + "title": "GetPayment", + "slug": "getpayment" }, "depth": 2, "children": [ @@ -263,10 +692,127 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "singleLineComment": ["//"], "name": "Java" }, - "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithCreditCardServlet.java", - "projectPath": "PaymentWithCreditCardServlet.java", - "targetPath": "PaymentWithCreditCardServlet", - "title": "PaymentWithCreditCardServlet" + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithCreditCardServlet.java", + "projectPath": "PaymentWithCreditCardServlet.java", + "targetPath": "PaymentWithCreditCardServlet", + "title": "PaymentWithCreditCardServlet" + }, + "depth": 1, + "outline": [ + { + "type": "heading", + "data": { + "level": 2, + "title": "Load Configuration", + "slug": "load-configuration" + }, + "depth": 2 + }, { + "type": "heading", + "data": { + "level": 2, + "title": "Create", + "slug": "create" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "Address", + "slug": "address" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "CreditCard", + "slug": "creditcard" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Transaction", + "slug": "transaction" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "FundingInstrument", + "slug": "fundinginstrument" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payer", + "slug": "payer" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payment", + "slug": "payment" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + } + ] + } + ] + }, { + "type": "file", + "data": { + "language": { + "nameMatchers": [".java"], + "pygmentsLexer": "java", + "singleLineComment": ["//"], + "name": "Java" + }, + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithPayPalServlet.java", + "projectPath": "PaymentWithPayPalServlet.java", + "targetPath": "PaymentWithPayPalServlet", + "title": "PaymentWithPayPalServlet" }, "depth": 1, "outline": [ @@ -291,24 +837,24 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "Address", - "slug": "address" + "title": "AccessToken", + "slug": "accesstoken" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "CreditCard", - "slug": "creditcard" + "title": "Api Context", + "slug": "api-context" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "AmountDetails", - "slug": "amountdetails" + "title": "Details", + "slug": "details" }, "depth": 3 }, { @@ -327,14 +873,6 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "slug": "transaction" }, "depth": 3 - }, { - "type": "heading", - "data": { - "level": 3, - "title": "FundingInstrument", - "slug": "fundinginstrument" - }, - "depth": 3 }, { "type": "heading", "data": { @@ -355,16 +893,16 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "AccessToken", - "slug": "accesstoken" + "title": "Redirect URLs", + "slug": "redirect-urls" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Api Context", - "slug": "api-context" + "title": "Payment Approval Url", + "slug": "payment-approval-url" }, "depth": 3 } @@ -380,10 +918,10 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "singleLineComment": ["//"], "name": "Java" }, - "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithPayPalServlet.java", - "projectPath": "PaymentWithPayPalServlet.java", - "targetPath": "PaymentWithPayPalServlet", - "title": "PaymentWithPayPalServlet" + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithSavedCardServlet.java", + "projectPath": "PaymentWithSavedCardServlet.java", + "targetPath": "PaymentWithSavedCardServlet", + "title": "PaymentWithSavedCardServlet" }, "depth": 1, "outline": [ @@ -408,40 +946,40 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "AccessToken", - "slug": "accesstoken" + "title": "CreditCard", + "slug": "creditcard" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Api Context", - "slug": "api-context" + "title": "Details", + "slug": "details" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "AmountDetails", - "slug": "amountdetails" + "title": "Amount", + "slug": "amount" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Amount", - "slug": "amount" + "title": "Transaction", + "slug": "transaction" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Transaction", - "slug": "transaction" + "title": "FundingInstrument", + "slug": "fundinginstrument" }, "depth": 3 }, { @@ -464,16 +1002,16 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "Redirect URLs", - "slug": "redirect-urls" + "title": "AccessToken", + "slug": "accesstoken" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Payment Approval Url", - "slug": "payment-approval-url" + "title": "APIContext", + "slug": "apicontext" }, "depth": 3 } @@ -489,10 +1027,10 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "singleLineComment": ["//"], "name": "Java" }, - "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\PaymentWithSavedCardServlet.java", - "projectPath": "PaymentWithSavedCardServlet.java", - "targetPath": "PaymentWithSavedCardServlet", - "title": "PaymentWithSavedCardServlet" + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\RefundCaptureServlet.java", + "projectPath": "RefundCaptureServlet.java", + "targetPath": "RefundCaptureServlet", + "title": "RefundCaptureServlet" }, "depth": 1, "outline": [ @@ -508,8 +1046,8 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 2, - "title": "Create", - "slug": "create" + "title": "RefundCapture", + "slug": "refundcapture" }, "depth": 2, "children": [ @@ -517,16 +1055,67 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "CreditCard", - "slug": "creditcard" + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Authorization", + "slug": "authorization" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "AmountDetails", - "slug": "amountdetails" + "title": "Capture", + "slug": "capture" + }, + "depth": 3 + } + ] + }, { + "type": "heading", + "data": { + "level": 2, + "title": "IsFinalCapture", + "slug": "isfinalcapture" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" }, "depth": 3 }, { @@ -549,40 +1138,40 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 "type": "heading", "data": { "level": 3, - "title": "FundingInstrument", - "slug": "fundinginstrument" + "title": "Address", + "slug": "address" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Payer", - "slug": "payer" + "title": "CreditCard", + "slug": "creditcard" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "Payment", - "slug": "payment" + "title": "FundingInstrument", + "slug": "fundinginstrument" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "AccessToken", - "slug": "accesstoken" + "title": "Payer", + "slug": "payer" }, "depth": 3 }, { "type": "heading", "data": { "level": 3, - "title": "APIContext", - "slug": "apicontext" + "title": "Payment", + "slug": "payment" }, "depth": 3 } @@ -666,6 +1255,131 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3 ] } ] + }, { + "type": "file", + "data": { + "language": { + "nameMatchers": [".java"], + "pygmentsLexer": "java", + "singleLineComment": ["//"], + "name": "Java" + }, + "sourcePath": "c:\\repos\\git-paypal\\groc\\sample-code\\VoidAuthorizationServlet.java", + "projectPath": "VoidAuthorizationServlet.java", + "targetPath": "VoidAuthorizationServlet", + "title": "VoidAuthorizationServlet" + }, + "depth": 1, + "outline": [ + { + "type": "heading", + "data": { + "level": 2, + "title": "Load Configuration", + "slug": "load-configuration" + }, + "depth": 2 + }, { + "type": "heading", + "data": { + "level": 2, + "title": "VoidAuthorization", + "slug": "voidauthorization" + }, + "depth": 2, + "children": [ + { + "type": "heading", + "data": { + "level": 3, + "title": "AccessToken", + "slug": "accesstoken" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Api Context", + "slug": "api-context" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Authorization", + "slug": "authorization" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Details", + "slug": "details" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Amount", + "slug": "amount" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Transaction", + "slug": "transaction" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Address", + "slug": "address" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "CreditCard", + "slug": "creditcard" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "FundingInstrument", + "slug": "fundinginstrument" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payer", + "slug": "payer" + }, + "depth": 3 + }, { + "type": "heading", + "data": { + "level": 3, + "title": "Payment", + "slug": "payment" + }, + "depth": 3 + } + ] + } + ] } ]; diff --git a/rest-api-sdk/pom.xml b/rest-api-sdk/pom.xml index c02ea684..fd1df0bf 100644 --- a/rest-api-sdk/pom.xml +++ b/rest-api-sdk/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.paypal.sdk rest-api-sdk - 0.5.2 + 0.7.0 jar REST API SDK PayPal SDK for integrating with the REST APIs @@ -28,24 +28,29 @@ UTF-8 - - com.google.code.gson - gson - 2.2.2 - org.testng testng 6.3.1 + test com.paypal.sdk paypal-core - 1.2 + 1.4.3 + + org.apache.maven.plugins + maven-compiler-plugin + 3.0 + + 1.5 + 1.5 + + org.apache.maven.plugins maven-source-plugin @@ -89,6 +94,12 @@ coverage + + + + env.BUILD_NUMBER + + net.sourceforge.cobertura @@ -96,7 +107,7 @@ 1.9.4.1 - + org.codehaus.mojo @@ -108,9 +119,17 @@ xml + + + package + + cobertura + + + - + diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Address.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Address.java index 29974d5d..fe8b55bf 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Address.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Address.java @@ -1,168 +1,182 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class Address extends Resource { +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Address { /** - * - */ + * Line 1 of the Address (eg. number, street, etc). + */ private String line1; - + /** - * - */ + * Optional line 2 of the Address (eg. suite, apt #, etc.). + */ private String line2; - + /** - * - */ + * City name. + */ private String city; - + /** - * - */ - private String state; - + * 2 letter country code. + */ + private String countryCode; + /** - * - */ + * Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. + */ private String postalCode; - - /** - * - */ - private String countryCode; - + /** - * - */ - private String type; - + * 2 letter code for US states, and the equivalent for other countries. + */ + private String state; + /** - * - */ + * Phone number in E.123 format. + */ private String phone; - + /** - * Constructor + * Default Constructor */ public Address() { - - } + } /** - * Getter for line1 + * Parameterized Constructor */ - public String getLine1() { - return line1; + public Address(String line1, String city, String countryCode, String state) { + this.line1 = line1; + this.city = city; + this.countryCode = countryCode; + this.state = state; } + /** - * Setter for line1; + * Setter for line1 */ - public void setLine1(String line1) { + public Address setLine1(String line1) { this.line1 = line1; - } - /** - * Getter for line2 - */ - public String getLine2() { - return line2; + return this; } /** - * Setter for line2; + * Getter for line1 */ - public void setLine2(String line2) { - this.line2 = line2; + public String getLine1() { + return this.line1; } + + /** - * Getter for city + * Setter for line2 */ - public String getCity() { - return city; + public Address setLine2(String line2) { + this.line2 = line2; + return this; } /** - * Setter for city; + * Getter for line2 */ - public void setCity(String city) { - this.city = city; + public String getLine2() { + return this.line2; } + + /** - * Getter for state + * Setter for city */ - public String getState() { - return state; + public Address setCity(String city) { + this.city = city; + return this; } /** - * Setter for state; + * Getter for city */ - public void setState(String state) { - this.state = state; + public String getCity() { + return this.city; } + + /** - * Getter for postalCode + * Setter for countryCode */ - public String getPostalCode() { - return postalCode; + public Address setCountryCode(String countryCode) { + this.countryCode = countryCode; + return this; } /** - * Setter for postalCode; + * Getter for countryCode */ - public void setPostalCode(String postalCode) { - this.postalCode = postalCode; + public String getCountryCode() { + return this.countryCode; } + + /** - * Getter for countryCode + * Setter for postalCode */ - public String getCountryCode() { - return countryCode; + public Address setPostalCode(String postalCode) { + this.postalCode = postalCode; + return this; } /** - * Setter for countryCode; + * Getter for postalCode */ - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; + public String getPostalCode() { + return this.postalCode; } + + /** - * Getter for type + * Setter for state */ - public String getType() { - return type; + public Address setState(String state) { + this.state = state; + return this; } /** - * Setter for type; + * Getter for state */ - public void setType(String type) { - this.type = type; + public String getState() { + return this.state; } + + /** - * Getter for phone + * Setter for phone */ - public String getPhone() { - return phone; + public Address setPhone(String phone) { + this.phone = phone; + return this; } /** - * Setter for phone; + * Getter for phone */ - public void setPhone(String phone) { - this.phone = phone; + public String getPhone() { + return this.phone; } - - - /** * Returns a JSON string corresponding to object state * @@ -171,10 +185,9 @@ public void setPhone(String phone) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Amount.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Amount.java index b45f947f..4dc3ed3d 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Amount.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Amount.java @@ -1,79 +1,97 @@ package com.paypal.api.payments; -import com.paypal.api.payments.AmountDetails; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class Amount extends Resource { +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Details; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Amount { /** - * - */ - private String total; - - /** - * - */ + * 3 letter currency code + */ private String currency; - + /** - * - */ - private AmountDetails details; - + * Total amount charged from the Payer account (or card) to Payee. In case of a refund, this is the refunded amount to the original Payer from Payee account. + */ + private String total; + + /** + * Additional details of the payment amount. + */ + private Details details; + /** - * Constructor + * Default Constructor */ public Amount() { - - } + } /** - * Getter for total + * Parameterized Constructor */ - public String getTotal() { - return total; + public Amount(String currency, String total) { + this.currency = currency; + this.total = total; } + /** - * Setter for total; + * Setter for currency */ - public void setTotal(String total) { - this.total = total; + public Amount setCurrency(String currency) { + this.currency = currency; + return this; } + /** * Getter for currency */ public String getCurrency() { - return currency; + return this.currency; + } + + + /** + * Setter for total + */ + public Amount setTotal(String total) { + this.total = total; + return this; } /** - * Setter for currency; + * Getter for total */ - public void setCurrency(String currency) { - this.currency = currency; + public String getTotal() { + return this.total; } + + /** - * Getter for details + * Setter for details */ - public AmountDetails getDetails() { - return details; + public Amount setDetails(Details details) { + this.details = details; + return this; } /** - * Setter for details; + * Getter for details */ - public void setDetails(AmountDetails details) { - this.details = details; + public Details getDetails() { + return this.details; } - - - /** * Returns a JSON string corresponding to object state * @@ -82,10 +100,9 @@ public void setDetails(AmountDetails details) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/AmountDetails.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/AmountDetails.java deleted file mode 100644 index 09bdd688..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/AmountDetails.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class AmountDetails extends Resource { - - - /** - * - */ - private String subtotal; - - /** - * - */ - private String tax; - - /** - * - */ - private String shipping; - - /** - * - */ - private String fee; - - /** - * Constructor - */ - public AmountDetails() { - - } - - /** - * Getter for subtotal - */ - public String getSubtotal() { - return subtotal; - } - - /** - * Setter for subtotal; - */ - public void setSubtotal(String subtotal) { - this.subtotal = subtotal; - } - /** - * Getter for tax - */ - public String getTax() { - return tax; - } - - /** - * Setter for tax; - */ - public void setTax(String tax) { - this.tax = tax; - } - /** - * Getter for shipping - */ - public String getShipping() { - return shipping; - } - - /** - * Setter for shipping; - */ - public void setShipping(String shipping) { - this.shipping = shipping; - } - /** - * Getter for fee - */ - public String getFee() { - return fee; - } - - /** - * Setter for fee; - */ - public void setFee(String fee) { - this.fee = fee; - } - - - - - /** - * Returns a JSON string corresponding to object state - * - * @return JSON representation - */ - public String toJSON() { - return JSONFormatter.toJSON(this); - } - - @Override - public String toString() { - return toJSON(); - } - -} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Authorization.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Authorization.java index c778523e..6b7e5ff5 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Authorization.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Authorization.java @@ -1,153 +1,326 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Links; import java.util.List; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class Authorization extends Resource { +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Authorization { /** - * - */ + * Identifier of the authorization transaction. + */ private String id; - + /** - * - */ + * Time the resource was created. + */ private String createTime; - + /** - * - */ + * Time the resource was last updated. + */ private String updateTime; - + /** - * - */ + * Amount being authorized for. + */ + private Amount amount; + + /** + * State of the authorization transaction. + */ private String state; + + /** + * ID of the Payment resource that this transaction is based on. + */ + private String parentPayment; + + /** + * Date/Time until which funds may be captured against this resource. + */ + private String validUntil; + + /** + * + */ + private List links; + + /** + * Returns the last request sent to the Service + * + * @return Last request sent to the server + */ + public static String getLastRequest() { + return PayPalResource.getLastRequest(); + } /** + * Returns the last response returned by the Service * - */ - private Amount amount; + * @return Last response got from the Service + */ + public static String getLastResponse() { + return PayPalResource.getLastResponse(); + } /** + * Initialize using InputStream(of a Properties file) * - */ - private String parentPayment; + * @param is + * InputStream + * @throws PayPalRESTException + */ + public static void initConfig(InputStream is) throws PayPalRESTException { + PayPalResource.initConfig(is); + } /** + * Initialize using a File(Properties file) * - */ - private List links; + * @param file + * File object of a properties entity + * @throws PayPalRESTException + */ + public static void initConfig(File file) throws PayPalRESTException { + PayPalResource.initConfig(file); + } /** - * Constructor + * Initialize using Properties + * + * @param properties + * Properties object + */ + public static void initConfig(Properties properties) { + PayPalResource.initConfig(properties); + } + /** + * Default Constructor */ public Authorization() { + } - } + /** + * Setter for id + */ + public Authorization setId(String id) { + this.id = id; + return this; + } + /** * Getter for id */ public String getId() { - return id; + return this.id; } - + + /** - * Setter for id; + * Setter for createTime */ - public void setId(String id) { - this.id = id; + public Authorization setCreateTime(String createTime) { + this.createTime = createTime; + return this; } + /** * Getter for createTime */ public String getCreateTime() { - return createTime; + return this.createTime; } - + + /** - * Setter for createTime; + * Setter for updateTime */ - public void setCreateTime(String createTime) { - this.createTime = createTime; + public Authorization setUpdateTime(String updateTime) { + this.updateTime = updateTime; + return this; } + /** * Getter for updateTime */ public String getUpdateTime() { - return updateTime; + return this.updateTime; } - + + /** - * Setter for updateTime; + * Setter for amount */ - public void setUpdateTime(String updateTime) { - this.updateTime = updateTime; + public Authorization setAmount(Amount amount) { + this.amount = amount; + return this; } + /** - * Getter for state + * Getter for amount */ - public String getState() { - return state; + public Amount getAmount() { + return this.amount; } - + + /** - * Setter for state; + * Setter for state */ - public void setState(String state) { + public Authorization setState(String state) { this.state = state; + return this; } + /** - * Getter for amount + * Getter for state */ - public Amount getAmount() { - return amount; + public String getState() { + return this.state; } - + + /** - * Setter for amount; + * Setter for parentPayment */ - public void setAmount(Amount amount) { - this.amount = amount; + public Authorization setParentPayment(String parentPayment) { + this.parentPayment = parentPayment; + return this; } + /** * Getter for parentPayment */ public String getParentPayment() { - return parentPayment; + return this.parentPayment; + } + + + /** + * Setter for validUntil + */ + public Authorization setValidUntil(String validUntil) { + this.validUntil = validUntil; + return this; } /** - * Setter for parentPayment; + * Getter for validUntil */ - public void setParentPayment(String parentPayment) { - this.parentPayment = parentPayment; + public String getValidUntil() { + return this.validUntil; } + + /** - * Getter for links + * Setter for links */ - public List getLinks() { - return links; + public Authorization setLinks(List links) { + this.links = links; + return this; } /** - * Setter for links; + * Getter for links */ - public void setLinks(List links) { - this.links = links; + public List getLinks() { + return this.links; } + /** + * Obtain the Authorization transaction resource for the given identifier. + */ + public static Authorization get(String accessToken, String authorizationId) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, authorizationId); + } + + /** + * Obtain the Authorization transaction resource for the given identifier. + */ + public static Authorization get(APIContext apiContext, String authorizationId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (authorizationId == null) { + throw new IllegalArgumentException("authorizationId cannot be null"); + } + Object[] parameters = new Object[] {authorizationId}; + String pattern = "v1/payments/authorization/{0}"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Authorization.class); + } + + /** + * Creates (and processes) a new Capture Transaction added as a related resource. + */ + public Capture capture(String accessToken, Capture capture) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return capture(apiContext, capture); + } + + /** + * Creates (and processes) a new Capture Transaction added as a related resource. + */ + public Capture capture(APIContext apiContext, Capture capture) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (this.getId() == null) { + throw new IllegalArgumentException("Id cannot be null"); + } + if (capture == null) { + throw new IllegalArgumentException("capture cannot be null"); + } + Object[] parameters = new Object[] {this.getId()}; + String pattern = "v1/payments/authorization/{0}/capture"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = capture.toJSON(); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Capture.class); + } + + /** + * Voids (cancels) an Authorization. + */ + public Authorization doVoid(String accessToken) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return doVoid(apiContext); + } + + /** + * Voids (cancels) an Authorization. + */ + public Authorization doVoid(APIContext apiContext) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (this.getId() == null) { + throw new IllegalArgumentException("Id cannot be null"); + } + Object[] parameters = new Object[] {this.getId()}; + String pattern = "v1/payments/authorization/{0}/void"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Authorization.class); + } + /** * Returns a JSON string corresponding to object state * @@ -156,10 +329,9 @@ public void setLinks(List links) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Capture.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Capture.java index 953d56e0..1eaa3e61 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Capture.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Capture.java @@ -1,189 +1,300 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Links; import java.util.List; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class Capture extends Resource { +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Capture { /** - * - */ + * Identifier of the Capture transaction. + */ private String id; - + /** - * - */ + * Time the resource was created. + */ private String createTime; - + /** - * - */ + * Time the resource was last updated. + */ private String updateTime; - + /** - * - */ + * Amount being captured. If no amount is specified, amount is used from the authorization being captured. If amount is same as the amount that's authorized for, the state of the authorization changes to captured. If not, the state of the authorization changes to partially_captured. Alternatively, you could indicate a final capture by seting the is_final_capture flag to true. + */ + private Amount amount; + + /** + * whether this is a final capture for the given authorization or not. If it's final, all the remaining funds held by the authorization, will be released in the funding instrument. + */ + private Boolean isFinalCapture; + + /** + * State of the capture transaction. + */ private String state; - + + /** + * ID of the Payment resource that this transaction is based on. + */ + private String parentPayment; + /** * - */ - private Amount amount; - + */ + private List links; + /** + * Returns the last request sent to the Service * - */ - private String parentPayment; + * @return Last request sent to the server + */ + public static String getLastRequest() { + return PayPalResource.getLastRequest(); + } /** + * Returns the last response returned by the Service * - */ - private String authorizationId; + * @return Last response got from the Service + */ + public static String getLastResponse() { + return PayPalResource.getLastResponse(); + } /** + * Initialize using InputStream(of a Properties file) * - */ - private String description; + * @param is + * InputStream + * @throws PayPalRESTException + */ + public static void initConfig(InputStream is) throws PayPalRESTException { + PayPalResource.initConfig(is); + } /** + * Initialize using a File(Properties file) * - */ - private List links; + * @param file + * File object of a properties entity + * @throws PayPalRESTException + */ + public static void initConfig(File file) throws PayPalRESTException { + PayPalResource.initConfig(file); + } /** - * Constructor + * Initialize using Properties + * + * @param properties + * Properties object + */ + public static void initConfig(Properties properties) { + PayPalResource.initConfig(properties); + } + /** + * Default Constructor */ public Capture() { + } - } + /** + * Setter for id + */ + public Capture setId(String id) { + this.id = id; + return this; + } + /** * Getter for id */ public String getId() { - return id; + return this.id; } - + + /** - * Setter for id; + * Setter for createTime */ - public void setId(String id) { - this.id = id; + public Capture setCreateTime(String createTime) { + this.createTime = createTime; + return this; } + /** * Getter for createTime */ public String getCreateTime() { - return createTime; + return this.createTime; } - + + /** - * Setter for createTime; + * Setter for updateTime */ - public void setCreateTime(String createTime) { - this.createTime = createTime; + public Capture setUpdateTime(String updateTime) { + this.updateTime = updateTime; + return this; } + /** * Getter for updateTime */ public String getUpdateTime() { - return updateTime; + return this.updateTime; + } + + + /** + * Setter for amount + */ + public Capture setAmount(Amount amount) { + this.amount = amount; + return this; } /** - * Setter for updateTime; + * Getter for amount */ - public void setUpdateTime(String updateTime) { - this.updateTime = updateTime; + public Amount getAmount() { + return this.amount; } + + /** - * Getter for state + * Setter for isFinalCapture */ - public String getState() { - return state; + public Capture setIsFinalCapture(Boolean isFinalCapture) { + this.isFinalCapture = isFinalCapture; + return this; } /** - * Setter for state; + * Getter for isFinalCapture */ - public void setState(String state) { - this.state = state; + public Boolean getIsFinalCapture() { + return this.isFinalCapture; } + + /** - * Getter for amount + * Setter for state */ - public Amount getAmount() { - return amount; + public Capture setState(String state) { + this.state = state; + return this; } /** - * Setter for amount; + * Getter for state */ - public void setAmount(Amount amount) { - this.amount = amount; + public String getState() { + return this.state; } + + /** - * Getter for parentPayment + * Setter for parentPayment */ - public String getParentPayment() { - return parentPayment; + public Capture setParentPayment(String parentPayment) { + this.parentPayment = parentPayment; + return this; } /** - * Setter for parentPayment; + * Getter for parentPayment */ - public void setParentPayment(String parentPayment) { - this.parentPayment = parentPayment; + public String getParentPayment() { + return this.parentPayment; } + + /** - * Getter for authorizationId + * Setter for links */ - public String getAuthorizationId() { - return authorizationId; + public Capture setLinks(List links) { + this.links = links; + return this; } /** - * Setter for authorizationId; + * Getter for links */ - public void setAuthorizationId(String authorizationId) { - this.authorizationId = authorizationId; + public List getLinks() { + return this.links; } + + /** - * Getter for description + * Obtain the Capture transaction resource for the given identifier. */ - public String getDescription() { - return description; + public static Capture get(String accessToken, String captureId) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, captureId); } /** - * Setter for description; + * Obtain the Capture transaction resource for the given identifier. */ - public void setDescription(String description) { - this.description = description; + public static Capture get(APIContext apiContext, String captureId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (captureId == null) { + throw new IllegalArgumentException("captureId cannot be null"); + } + Object[] parameters = new Object[] {captureId}; + String pattern = "v1/payments/capture/{0}"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Capture.class); } + + /** - * Getter for links + * Creates (and processes) a new Refund Transaction added as a related resource. */ - public List getLinks() { - return links; + public Refund refund(String accessToken, Refund refund) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return refund(apiContext, refund); } /** - * Setter for links; + * Creates (and processes) a new Refund Transaction added as a related resource. */ - public void setLinks(List links) { - this.links = links; + public Refund refund(APIContext apiContext, Refund refund) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (this.getId() == null) { + throw new IllegalArgumentException("Id cannot be null"); + } + if (refund == null) { + throw new IllegalArgumentException("refund cannot be null"); + } + Object[] parameters = new Object[] {this.getId()}; + String pattern = "v1/payments/capture/{0}/refund"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = refund.toJSON(); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Refund.class); } - - - - + /** * Returns a JSON string corresponding to object state * @@ -192,10 +303,9 @@ public void setLinks(List links) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCard.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCard.java index 07f1e11d..88e33b9e 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCard.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCard.java @@ -1,89 +1,87 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Address; +import com.paypal.api.payments.Links; import java.util.List; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.PayPalResource; import com.paypal.core.rest.HttpMethod; -import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.RESTUtil; -import com.paypal.core.rest.JSONFormatter; +import com.paypal.core.rest.QueryParameters; import com.paypal.core.rest.APIContext; import java.io.File; import java.io.InputStream; import java.util.Properties; -/** - * - */ -public class CreditCard extends Resource { - +public class CreditCard { /** - * - */ + * ID of the credit card being saved for later use. + */ private String id; - - /** - * - */ - private String validUntil; - - /** - * - */ - private String state; - + /** - * - */ - private String payerId; - + * Card number. + */ + private String number; + /** - * - */ + * Type of the Card (eg. Visa, Mastercard, etc.). + */ private String type; - - /** - * - */ - private String number; - + /** - * - */ - private String expireMonth; - + * card expiry month with value 1 - 12. + */ + private int expireMonth; + /** - * - */ - private String expireYear; - + * 4 digit card expiry year + */ + private int expireYear; + /** - * - */ + * Card validation code. Only supported when making a Payment but not when saving a credit card for future use. + */ private String cvv2; - + /** - * - */ + * Card holder's first name. + */ private String firstName; - + /** - * - */ + * Card holder's last name. + */ private String lastName; - + /** - * - */ + * Billing Address associated with this card. + */ private Address billingAddress; - + + /** + * A unique identifier of the payer generated and provided by the facilitator. This is required when creating or using a tokenized funding instrument. + */ + private String payerId; + + /** + * State of the funding instrument. + */ + private String state; + + /** + * Date/Time until this resource can be used fund a payment. + */ + private String validUntil; + /** * - */ - private List links; - + */ + private List links; + /** * Returns the last request sent to the Service * @@ -101,7 +99,7 @@ public static String getLastRequest() { public static String getLastResponse() { return PayPalResource.getLastResponse(); } - + /** * Initialize using InputStream(of a Properties file) * @@ -133,195 +131,233 @@ public static void initConfig(File file) throws PayPalRESTException { public static void initConfig(Properties properties) { PayPalResource.initConfig(properties); } - - /** - * Constructor + * Default Constructor */ public CreditCard() { - - } + } /** - * Getter for id + * Parameterized Constructor */ - public String getId() { - return id; + public CreditCard(String number, String type, int expireMonth, int expireYear) { + this.number = number; + this.type = type; + this.expireMonth = expireMonth; + this.expireYear = expireYear; } + /** - * Setter for id; + * Setter for id */ - public void setId(String id) { + public CreditCard setId(String id) { this.id = id; + return this; } + /** - * Getter for validUntil + * Getter for id */ - public String getValidUntil() { - return validUntil; + public String getId() { + return this.id; + } + + + /** + * Setter for number + */ + public CreditCard setNumber(String number) { + this.number = number; + return this; } /** - * Setter for validUntil; + * Getter for number */ - public void setValidUntil(String validUntil) { - this.validUntil = validUntil; + public String getNumber() { + return this.number; } + + /** - * Getter for state + * Setter for type */ - public String getState() { - return state; + public CreditCard setType(String type) { + this.type = type; + return this; } /** - * Setter for state; + * Getter for type */ - public void setState(String state) { - this.state = state; + public String getType() { + return this.type; } + + /** - * Getter for payerId + * Setter for expireMonth */ - public String getPayerId() { - return payerId; + public CreditCard setExpireMonth(int expireMonth) { + this.expireMonth = expireMonth; + return this; } /** - * Setter for payerId; + * Getter for expireMonth */ - public void setPayerId(String payerId) { - this.payerId = payerId; + public int getExpireMonth() { + return this.expireMonth; } + + /** - * Getter for type + * Setter for expireYear */ - public String getType() { - return type; + public CreditCard setExpireYear(int expireYear) { + this.expireYear = expireYear; + return this; } /** - * Setter for type; + * Getter for expireYear */ - public void setType(String type) { - this.type = type; + public int getExpireYear() { + return this.expireYear; } + + /** - * Getter for number + * Setter for cvv2 */ - public String getNumber() { - return number; + public CreditCard setCvv2(String cvv2) { + this.cvv2 = cvv2; + return this; } /** - * Setter for number; + * Getter for cvv2 */ - public void setNumber(String number) { - this.number = number; + public String getCvv2() { + return this.cvv2; } + + /** - * Getter for expireMonth + * Setter for firstName */ - public String getExpireMonth() { - return expireMonth; + public CreditCard setFirstName(String firstName) { + this.firstName = firstName; + return this; } /** - * Setter for expireMonth; + * Getter for firstName */ - public void setExpireMonth(String expireMonth) { - this.expireMonth = expireMonth; + public String getFirstName() { + return this.firstName; } + + /** - * Getter for expireYear + * Setter for lastName */ - public String getExpireYear() { - return expireYear; + public CreditCard setLastName(String lastName) { + this.lastName = lastName; + return this; } /** - * Setter for expireYear; + * Getter for lastName */ - public void setExpireYear(String expireYear) { - this.expireYear = expireYear; + public String getLastName() { + return this.lastName; } + + /** - * Getter for cvv2 + * Setter for billingAddress */ - public String getCvv2() { - return cvv2; + public CreditCard setBillingAddress(Address billingAddress) { + this.billingAddress = billingAddress; + return this; } /** - * Setter for cvv2; + * Getter for billingAddress */ - public void setCvv2(String cvv2) { - this.cvv2 = cvv2; + public Address getBillingAddress() { + return this.billingAddress; } + + /** - * Getter for firstName + * Setter for payerId */ - public String getFirstName() { - return firstName; + public CreditCard setPayerId(String payerId) { + this.payerId = payerId; + return this; } /** - * Setter for firstName; + * Getter for payerId */ - public void setFirstName(String firstName) { - this.firstName = firstName; + public String getPayerId() { + return this.payerId; } + + /** - * Getter for lastName + * Setter for state */ - public String getLastName() { - return lastName; + public CreditCard setState(String state) { + this.state = state; + return this; } /** - * Setter for lastName; + * Getter for state */ - public void setLastName(String lastName) { - this.lastName = lastName; + public String getState() { + return this.state; } + + /** - * Getter for billingAddress + * Setter for validUntil */ - public Address getBillingAddress() { - return billingAddress; + public CreditCard setValidUntil(String validUntil) { + this.validUntil = validUntil; + return this; } /** - * Setter for billingAddress; + * Getter for validUntil */ - public void setBillingAddress(Address billingAddress) { - this.billingAddress = billingAddress; + public String getValidUntil() { + return this.validUntil; } + + /** - * Getter for links + * Setter for links */ - public List getLinks() { - return links; + public CreditCard setLinks(List links) { + this.links = links; + return this; } /** - * Setter for links; + * Getter for links */ - public void setLinks(List links) { - this.links = links; + public List getLinks() { + return this.links; } - - /** - * Create call for CreditCard. - * @param accessToken - * AccessToken used for the API call - * @HttpMethod POST - * @URIpath v1/vault/credit-card - * @return CreditCard + * Creates a new Credit Card Resource (aka Tokenize). */ public CreditCard create(String accessToken) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); @@ -329,39 +365,72 @@ public CreditCard create(String accessToken) throws PayPalRESTException { } /** - * Create call for CreditCard. - * @param apiContext - * APIContext used for the API call - * @HttpMethod POST - * @URIpath v1/vault/credit-card - * @return CreditCard + * Creates a new Credit Card Resource (aka Tokenize). */ public CreditCard create(APIContext apiContext) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } String resourcePath = "v1/vault/credit-card"; - String payLoad = this.toJSON(); + String payLoad = this.toJSON(); return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, CreditCard.class); } + /** - * Get call for CreditCard. - * @param accessToken - * AccessToken used for the API call - * @param creditCardId - * @HttpMethod GET - * @URIpath v1/vault/credit-card/:creditCardId - * @return CreditCard + * Obtain the Credit Card resource for the given identifier. */ public static CreditCard get(String accessToken, String creditCardId) throws PayPalRESTException { - if ((creditCardId == null) || (creditCardId.length() <= 0)) { - throw new IllegalArgumentException("creditCardId cannot be null or empty"); + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, creditCardId); + } + + /** + * Obtain the Credit Card resource for the given identifier. + */ + public static CreditCard get(APIContext apiContext, String creditCardId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); } + if (creditCardId == null) { + throw new IllegalArgumentException("creditCardId cannot be null"); + } + Object[] parameters = new Object[] {creditCardId}; String pattern = "v1/vault/credit-card/{0}"; - Object[] parameters = new Object[] { creditCardId }; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, CreditCard.class); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, CreditCard.class); } + + /** + * Delete the Credit Card resource for the given identifier. Returns 204 No Content when the card is deleted successfully. + */ + public void delete(String accessToken) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + delete(apiContext); + return; + } + + /** + * Delete the Credit Card resource for the given identifier. Returns 204 No Content when the card is deleted successfully. + */ + public void delete(APIContext apiContext) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (this.getId() == null) { + throw new IllegalArgumentException("Id cannot be null"); + } + apiContext.setMaskRequestId(true); + Object[] parameters = new Object[] {this.getId()}; + String pattern = "v1/vault/credit-card/{0}"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + PayPalResource.configureAndExecute(apiContext, HttpMethod.DELETE, resourcePath, payLoad, null); + return; + } + /** * Returns a JSON string corresponding to object state * @@ -370,10 +439,9 @@ public static CreditCard get(String accessToken, String creditCardId) throws Pay public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardHistory.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardHistory.java new file mode 100644 index 00000000..ff2088dd --- /dev/null +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardHistory.java @@ -0,0 +1,101 @@ +package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.CreditCard; +import java.util.List; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +public class CreditCardHistory { + + /** + * A list of credit card resources + */ + private List creditCards; + + /** + * Number of items returned in each range of results. Note that the last results range could have fewer items than the requested number of items. + */ + private int count; + + /** + * Identifier of the next element to get the next range of results. + */ + private String nextId; + + /** + * Default Constructor + */ + public CreditCardHistory() { + } + + + /** + * Setter for creditCards + */ + public CreditCardHistory setCreditCards(List creditCards) { + this.creditCards = creditCards; + return this; + } + + /** + * Getter for creditCards + */ + public List getCreditCards() { + return this.creditCards; + } + + + /** + * Setter for count + */ + public CreditCardHistory setCount(int count) { + this.count = count; + return this; + } + + /** + * Getter for count + */ + public int getCount() { + return this.count; + } + + + /** + * Setter for nextId + */ + public CreditCardHistory setNextId(String nextId) { + this.nextId = nextId; + return this; + } + + /** + * Getter for nextId + */ + public String getNextId() { + return this.nextId; + } + + /** + * Returns a JSON string corresponding to object state + * + * @return JSON representation + */ + public String toJSON() { + return JSONFormatter.toJSON(this); + } + + @Override + public String toString() { + return toJSON(); + } +} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardToken.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardToken.java index 3fb650de..c3c02aa3 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardToken.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/CreditCardToken.java @@ -1,60 +1,158 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class CreditCardToken extends Resource { +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class CreditCardToken { /** - * - */ + * ID of a previously saved Credit Card resource using /vault/credit-card API. + */ private String creditCardId; - + /** - * - */ + * The unique identifier of the payer used when saving this credit card using /vault/credit-card API. + */ private String payerId; - + + /** + * Last 4 digits of the card number from the saved card. + */ + private String last4; + + /** + * Type of the Card (eg. visa, mastercard, etc.) from the saved card. Please note that the values are always in lowercase and not meant to be used directly for display. + */ + private String type; + + /** + * card expiry month from the saved card with value 1 - 12 + */ + private int expireMonth; + /** - * Constructor + * 4 digit card expiry year from the saved card + */ + private int expireYear; + + /** + * Default Constructor */ public CreditCardToken() { + } - } + /** + * Parameterized Constructor + */ + public CreditCardToken(String creditCardId) { + this.creditCardId = creditCardId; + } + + /** + * Setter for creditCardId + */ + public CreditCardToken setCreditCardId(String creditCardId) { + this.creditCardId = creditCardId; + return this; + } + /** * Getter for creditCardId */ public String getCreditCardId() { - return creditCardId; + return this.creditCardId; } - + + /** - * Setter for creditCardId; + * Setter for payerId */ - public void setCreditCardId(String creditCardId) { - this.creditCardId = creditCardId; + public CreditCardToken setPayerId(String payerId) { + this.payerId = payerId; + return this; } + /** * Getter for payerId */ public String getPayerId() { - return payerId; + return this.payerId; + } + + + /** + * Setter for last4 + */ + public CreditCardToken setLast4(String last4) { + this.last4 = last4; + return this; } /** - * Setter for payerId; + * Getter for last4 */ - public void setPayerId(String payerId) { - this.payerId = payerId; + public String getLast4() { + return this.last4; + } + + + /** + * Setter for type + */ + public CreditCardToken setType(String type) { + this.type = type; + return this; + } + + /** + * Getter for type + */ + public String getType() { + return this.type; } + /** + * Setter for expireMonth + */ + public CreditCardToken setExpireMonth(int expireMonth) { + this.expireMonth = expireMonth; + return this; + } + + /** + * Getter for expireMonth + */ + public int getExpireMonth() { + return this.expireMonth; + } + /** + * Setter for expireYear + */ + public CreditCardToken setExpireYear(int expireYear) { + this.expireYear = expireYear; + return this; + } + + /** + * Getter for expireYear + */ + public int getExpireYear() { + return this.expireYear; + } + /** * Returns a JSON string corresponding to object state * @@ -63,10 +161,9 @@ public void setPayerId(String payerId) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Details.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Details.java new file mode 100644 index 00000000..ccf077c6 --- /dev/null +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Details.java @@ -0,0 +1,120 @@ +package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +public class Details { + + /** + * Amount being charged for shipping. + */ + private String shipping; + + /** + * Sub-total (amount) of items being paid for. + */ + private String subtotal; + + /** + * Amount being charged as tax. + */ + private String tax; + + /** + * Fee charged by PayPal. In case of a refund, this is the fee amount refunded to the original receipient of the payment. + */ + private String fee; + + /** + * Default Constructor + */ + public Details() { + } + + + /** + * Setter for shipping + */ + public Details setShipping(String shipping) { + this.shipping = shipping; + return this; + } + + /** + * Getter for shipping + */ + public String getShipping() { + return this.shipping; + } + + + /** + * Setter for subtotal + */ + public Details setSubtotal(String subtotal) { + this.subtotal = subtotal; + return this; + } + + /** + * Getter for subtotal + */ + public String getSubtotal() { + return this.subtotal; + } + + + /** + * Setter for tax + */ + public Details setTax(String tax) { + this.tax = tax; + return this; + } + + /** + * Getter for tax + */ + public String getTax() { + return this.tax; + } + + + /** + * Setter for fee + */ + public Details setFee(String fee) { + this.fee = fee; + return this; + } + + /** + * Getter for fee + */ + public String getFee() { + return this.fee; + } + + /** + * Returns a JSON string corresponding to object state + * + * @return JSON representation + */ + public String toJSON() { + return JSONFormatter.toJSON(this); + } + + @Override + public String toString() { + return toJSON(); + } +} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/FundingInstrument.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/FundingInstrument.java index ff51b45b..40c33d2e 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/FundingInstrument.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/FundingInstrument.java @@ -1,62 +1,69 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.CreditCard; import com.paypal.api.payments.CreditCardToken; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class FundingInstrument extends Resource { +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class FundingInstrument { /** - * - */ + * Credit Card information. + */ private CreditCard creditCard; - + /** - * - */ + * Credit Card information. + */ private CreditCardToken creditCardToken; - + /** - * Constructor + * Default Constructor */ public FundingInstrument() { + } - } /** - * Getter for creditCard + * Setter for creditCard */ - public CreditCard getCreditCard() { - return creditCard; + public FundingInstrument setCreditCard(CreditCard creditCard) { + this.creditCard = creditCard; + return this; } /** - * Setter for creditCard; + * Getter for creditCard */ - public void setCreditCard(CreditCard creditCard) { - this.creditCard = creditCard; + public CreditCard getCreditCard() { + return this.creditCard; } + + /** - * Getter for creditCardToken + * Setter for creditCardToken */ - public CreditCardToken getCreditCardToken() { - return creditCardToken; + public FundingInstrument setCreditCardToken(CreditCardToken creditCardToken) { + this.creditCardToken = creditCardToken; + return this; } /** - * Setter for creditCardToken; + * Getter for creditCardToken */ - public void setCreditCardToken(CreditCardToken creditCardToken) { - this.creditCardToken = creditCardToken; + public CreditCardToken getCreditCardToken() { + return this.creditCardToken; } - - - /** * Returns a JSON string corresponding to object state * @@ -65,10 +72,9 @@ public void setCreditCardToken(CreditCardToken creditCardToken) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/HyperSchema.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/HyperSchema.java new file mode 100644 index 00000000..78105023 --- /dev/null +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/HyperSchema.java @@ -0,0 +1,164 @@ +package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Links; +import java.util.List; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +public class HyperSchema { + + /** + * + */ + private List links; + + /** + * + */ + private String fragmentResolution; + + /** + * + */ + private Boolean readonly; + + /** + * + */ + private String contentEncoding; + + /** + * + */ + private String pathStart; + + /** + * + */ + private String mediaType; + + /** + * Default Constructor + */ + public HyperSchema() { + } + + + /** + * Setter for links + */ + public HyperSchema setLinks(List links) { + this.links = links; + return this; + } + + /** + * Getter for links + */ + public List getLinks() { + return this.links; + } + + + /** + * Setter for fragmentResolution + */ + public HyperSchema setFragmentResolution(String fragmentResolution) { + this.fragmentResolution = fragmentResolution; + return this; + } + + /** + * Getter for fragmentResolution + */ + public String getFragmentResolution() { + return this.fragmentResolution; + } + + + /** + * Setter for readonly + */ + public HyperSchema setReadonly(Boolean readonly) { + this.readonly = readonly; + return this; + } + + /** + * Getter for readonly + */ + public Boolean getReadonly() { + return this.readonly; + } + + + /** + * Setter for contentEncoding + */ + public HyperSchema setContentEncoding(String contentEncoding) { + this.contentEncoding = contentEncoding; + return this; + } + + /** + * Getter for contentEncoding + */ + public String getContentEncoding() { + return this.contentEncoding; + } + + + /** + * Setter for pathStart + */ + public HyperSchema setPathStart(String pathStart) { + this.pathStart = pathStart; + return this; + } + + /** + * Getter for pathStart + */ + public String getPathStart() { + return this.pathStart; + } + + + /** + * Setter for mediaType + */ + public HyperSchema setMediaType(String mediaType) { + this.mediaType = mediaType; + return this; + } + + /** + * Getter for mediaType + */ + public String getMediaType() { + return this.mediaType; + } + + /** + * Returns a JSON string corresponding to object state + * + * @return JSON representation + */ + public String toJSON() { + return JSONFormatter.toJSON(this); + } + + @Override + public String toString() { + return toJSON(); + } +} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Item.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Item.java index 7054c0b3..d08a6f1e 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Item.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Item.java @@ -1,114 +1,140 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class Item extends Resource { +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Item { /** - * - */ - private String name; - + * Number of items. + */ + private String quantity; + /** - * - */ - private String sku; - + * Name of the item. + */ + private String name; + /** - * - */ + * Cost of the item. + */ private String price; - + /** - * - */ + * 3-letter Currency Code + */ private String currency; - + /** - * - */ - private String quantity; - + * Number or code to identify the item in your catalog/records. + */ + private String sku; + /** - * Constructor + * Default Constructor */ public Item() { + } - } + /** + * Parameterized Constructor + */ + public Item(String quantity, String name, String price, String currency) { + this.quantity = quantity; + this.name = name; + this.price = price; + this.currency = currency; + } + /** - * Getter for name + * Setter for quantity */ - public String getName() { - return name; + public Item setQuantity(String quantity) { + this.quantity = quantity; + return this; } /** - * Setter for name; + * Getter for quantity */ - public void setName(String name) { - this.name = name; + public String getQuantity() { + return this.quantity; } + + /** - * Getter for sku + * Setter for name */ - public String getSku() { - return sku; + public Item setName(String name) { + this.name = name; + return this; } /** - * Setter for sku; + * Getter for name */ - public void setSku(String sku) { - this.sku = sku; + public String getName() { + return this.name; } + + /** - * Getter for price + * Setter for price */ - public String getPrice() { - return price; + public Item setPrice(String price) { + this.price = price; + return this; } /** - * Setter for price; + * Getter for price */ - public void setPrice(String price) { - this.price = price; + public String getPrice() { + return this.price; } + + /** - * Getter for currency + * Setter for currency */ - public String getCurrency() { - return currency; + public Item setCurrency(String currency) { + this.currency = currency; + return this; } /** - * Setter for currency; + * Getter for currency */ - public void setCurrency(String currency) { - this.currency = currency; + public String getCurrency() { + return this.currency; } + + /** - * Getter for quantity + * Setter for sku */ - public String getQuantity() { - return quantity; + public Item setSku(String sku) { + this.sku = sku; + return this; } /** - * Setter for quantity; + * Getter for sku */ - public void setQuantity(String quantity) { - this.quantity = quantity; + public String getSku() { + return this.sku; } - - - /** * Returns a JSON string corresponding to object state * @@ -117,10 +143,9 @@ public void setQuantity(String quantity) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/ItemList.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/ItemList.java index a7a4c318..819af479 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/ItemList.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/ItemList.java @@ -1,63 +1,70 @@ package com.paypal.api.payments; -import java.util.List; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Item; +import java.util.List; import com.paypal.api.payments.ShippingAddress; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class ItemList extends Resource { +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class ItemList { /** - * - */ + * List of items. + */ private List items; - + /** - * - */ + * Shipping address. + */ private ShippingAddress shippingAddress; - + /** - * Constructor + * Default Constructor */ public ItemList() { + } - } /** - * Getter for items + * Setter for items */ - public List getItems() { - return items; + public ItemList setItems(List items) { + this.items = items; + return this; } /** - * Setter for items; + * Getter for items */ - public void setItems(List items) { - this.items = items; + public List getItems() { + return this.items; } + + /** - * Getter for shippingAddress + * Setter for shippingAddress */ - public ShippingAddress getShippingAddress() { - return shippingAddress; + public ItemList setShippingAddress(ShippingAddress shippingAddress) { + this.shippingAddress = shippingAddress; + return this; } /** - * Setter for shippingAddress; + * Getter for shippingAddress */ - public void setShippingAddress(ShippingAddress shippingAddress) { - this.shippingAddress = shippingAddress; + public ShippingAddress getShippingAddress() { + return this.shippingAddress; } - - - /** * Returns a JSON string corresponding to object state * @@ -66,10 +73,9 @@ public void setShippingAddress(ShippingAddress shippingAddress) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Link.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Link.java deleted file mode 100644 index 30ec946d..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Link.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class Link extends Resource { - - - /** - * - */ - private String href; - - /** - * - */ - private String rel; - - /** - * - */ - private String method; - - /** - * Constructor - */ - public Link() { - - } - - /** - * Getter for href - */ - public String getHref() { - return href; - } - - /** - * Setter for href; - */ - public void setHref(String href) { - this.href = href; - } - /** - * Getter for rel - */ - public String getRel() { - return rel; - } - - /** - * Setter for rel; - */ - public void setRel(String rel) { - this.rel = rel; - } - /** - * Getter for method - */ - public String getMethod() { - return method; - } - - /** - * Setter for method; - */ - public void setMethod(String method) { - this.method = method; - } - - - - - /** - * Returns a JSON string corresponding to object state - * - * @return JSON representation - */ - public String toJSON() { - return JSONFormatter.toJSON(this); - } - - @Override - public String toString() { - return toJSON(); - } - -} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Links.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Links.java new file mode 100644 index 00000000..3d909aa5 --- /dev/null +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Links.java @@ -0,0 +1,171 @@ +package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.HyperSchema; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +public class Links { + + /** + * + */ + private String href; + + /** + * + */ + private String rel; + + /** + * + */ + private HyperSchema targetSchema; + + /** + * + */ + private String method; + + /** + * + */ + private String enctype; + + /** + * + */ + private HyperSchema schema; + + /** + * Default Constructor + */ + public Links() { + } + + /** + * Parameterized Constructor + */ + public Links(String href, String rel) { + this.href = href; + this.rel = rel; + } + + + /** + * Setter for href + */ + public Links setHref(String href) { + this.href = href; + return this; + } + + /** + * Getter for href + */ + public String getHref() { + return this.href; + } + + + /** + * Setter for rel + */ + public Links setRel(String rel) { + this.rel = rel; + return this; + } + + /** + * Getter for rel + */ + public String getRel() { + return this.rel; + } + + + /** + * Setter for targetSchema + */ + public Links setTargetSchema(HyperSchema targetSchema) { + this.targetSchema = targetSchema; + return this; + } + + /** + * Getter for targetSchema + */ + public HyperSchema getTargetSchema() { + return this.targetSchema; + } + + + /** + * Setter for method + */ + public Links setMethod(String method) { + this.method = method; + return this; + } + + /** + * Getter for method + */ + public String getMethod() { + return this.method; + } + + + /** + * Setter for enctype + */ + public Links setEnctype(String enctype) { + this.enctype = enctype; + return this; + } + + /** + * Getter for enctype + */ + public String getEnctype() { + return this.enctype; + } + + + /** + * Setter for schema + */ + public Links setSchema(HyperSchema schema) { + this.schema = schema; + return this; + } + + /** + * Getter for schema + */ + public HyperSchema getSchema() { + return this.schema; + } + + /** + * Returns a JSON string corresponding to object state + * + * @return JSON representation + */ + public String toJSON() { + return JSONFormatter.toJSON(this); + } + + @Override + public String toString() { + return toJSON(); + } +} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payee.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payee.java index e7822202..b1865812 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payee.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payee.java @@ -1,78 +1,97 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class Payee extends Resource { +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Payee { /** - * - */ - private String merchantId; - - /** - * - */ + * Email Address associated with the Payee's PayPal Account. If the provided email address is not associated with any PayPal Account, the payee can only receiver PayPal Wallet Payments. Direct Credit Card Payments will be denied due to card compliance requirements. + */ private String email; - + /** - * - */ + * Encrypted PayPal Account identifier for the Payee. + */ + private String merchantId; + + /** + * Phone number (in E.123 format) associated with the Payee's PayPal Account. If the provided phont number is not associated with any PayPal Account, the payee can only receiver PayPal Wallet Payments. Direct Credit Card Payments will be denied due to card compliance requirements. + */ private String phone; - + /** - * Constructor + * Default Constructor */ public Payee() { - - } + } /** - * Getter for merchantId + * Parameterized Constructor */ - public String getMerchantId() { - return merchantId; + public Payee(String email, String merchantId, String phone) { + this.email = email; + this.merchantId = merchantId; + this.phone = phone; } + /** - * Setter for merchantId; + * Setter for email */ - public void setMerchantId(String merchantId) { - this.merchantId = merchantId; + public Payee setEmail(String email) { + this.email = email; + return this; } + /** * Getter for email */ public String getEmail() { - return email; + return this.email; + } + + + /** + * Setter for merchantId + */ + public Payee setMerchantId(String merchantId) { + this.merchantId = merchantId; + return this; } /** - * Setter for email; + * Getter for merchantId */ - public void setEmail(String email) { - this.email = email; + public String getMerchantId() { + return this.merchantId; } + + /** - * Getter for phone + * Setter for phone */ - public String getPhone() { - return phone; + public Payee setPhone(String phone) { + this.phone = phone; + return this; } /** - * Setter for phone; + * Getter for phone */ - public void setPhone(String phone) { - this.phone = phone; + public String getPhone() { + return this.phone; } - - - /** * Returns a JSON string corresponding to object state * @@ -81,10 +100,9 @@ public void setPhone(String phone) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payer.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payer.java index 2cfd969f..a006bd50 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payer.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payer.java @@ -1,81 +1,98 @@ package com.paypal.api.payments; -import com.paypal.api.payments.PayerInfo; -import java.util.List; -import com.paypal.api.payments.FundingInstrument; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class Payer extends Resource { +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.FundingInstrument; +import java.util.List; +import com.paypal.api.payments.PayerInfo; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Payer { /** - * - */ + * Payment method being used - PayPal Wallet payment or Direct Credit card. + */ private String paymentMethod; - - /** - * - */ - private PayerInfo payerInfo; - + /** - * - */ + * List of funding instruments from where the funds of the current payment come from. Typically a credit card. + */ private List fundingInstruments; - + + /** + * Information related to the Payer. In case of PayPal Wallet payment, this information will be filled in by PayPal after the user approves the payment using their PayPal Wallet. + */ + private PayerInfo payerInfo; + /** - * Constructor + * Default Constructor */ public Payer() { - - } + } /** - * Getter for paymentMethod + * Parameterized Constructor */ - public String getPaymentMethod() { - return paymentMethod; + public Payer(String paymentMethod) { + this.paymentMethod = paymentMethod; } + /** - * Setter for paymentMethod; + * Setter for paymentMethod */ - public void setPaymentMethod(String paymentMethod) { + public Payer setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; + return this; } + /** - * Getter for payerInfo + * Getter for paymentMethod */ - public PayerInfo getPayerInfo() { - return payerInfo; + public String getPaymentMethod() { + return this.paymentMethod; } - + + /** - * Setter for payerInfo; + * Setter for fundingInstruments */ - public void setPayerInfo(PayerInfo payerInfo) { - this.payerInfo = payerInfo; + public Payer setFundingInstruments(List fundingInstruments) { + this.fundingInstruments = fundingInstruments; + return this; } + /** * Getter for fundingInstruments */ public List getFundingInstruments() { - return fundingInstruments; + return this.fundingInstruments; + } + + + /** + * Setter for payerInfo + */ + public Payer setPayerInfo(PayerInfo payerInfo) { + this.payerInfo = payerInfo; + return this; } /** - * Setter for fundingInstruments; + * Getter for payerInfo */ - public void setFundingInstruments(List fundingInstruments) { - this.fundingInstruments = fundingInstruments; + public PayerInfo getPayerInfo() { + return this.payerInfo; } - - - /** * Returns a JSON string corresponding to object state * @@ -84,10 +101,9 @@ public void setFundingInstruments(List fundingInstruments) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/PayerInfo.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/PayerInfo.java index 95ff3524..caf525a9 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/PayerInfo.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/PayerInfo.java @@ -1,133 +1,152 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Address; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class PayerInfo extends Resource { +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Address; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class PayerInfo { /** - * - */ + * Email address representing the Payer. + */ private String email; - + /** - * - */ + * First Name of the Payer from their PayPal Account. + */ private String firstName; - + /** - * - */ + * Last Name of the Payer from their PayPal Account. + */ private String lastName; - + /** - * - */ + * PayPal assigned Payer ID. + */ private String payerId; - - /** - * - */ - private Address shippingAddress; - + /** - * - */ + * Phone number representing the Payer. + */ private String phone; - + + /** + * Shipping address of the Payer from their PayPal Account. + */ + private Address shippingAddress; + /** - * Constructor + * Default Constructor */ public PayerInfo() { + } - } + /** + * Setter for email + */ + public PayerInfo setEmail(String email) { + this.email = email; + return this; + } + /** * Getter for email */ public String getEmail() { - return email; + return this.email; } - + + /** - * Setter for email; + * Setter for firstName */ - public void setEmail(String email) { - this.email = email; + public PayerInfo setFirstName(String firstName) { + this.firstName = firstName; + return this; } + /** * Getter for firstName */ public String getFirstName() { - return firstName; + return this.firstName; } - + + /** - * Setter for firstName; + * Setter for lastName */ - public void setFirstName(String firstName) { - this.firstName = firstName; + public PayerInfo setLastName(String lastName) { + this.lastName = lastName; + return this; } + /** * Getter for lastName */ public String getLastName() { - return lastName; + return this.lastName; } - + + /** - * Setter for lastName; + * Setter for payerId */ - public void setLastName(String lastName) { - this.lastName = lastName; + public PayerInfo setPayerId(String payerId) { + this.payerId = payerId; + return this; } + /** * Getter for payerId */ public String getPayerId() { - return payerId; + return this.payerId; } - + + /** - * Setter for payerId; + * Setter for phone */ - public void setPayerId(String payerId) { - this.payerId = payerId; - } - /** - * Getter for shippingAddress - */ - public Address getShippingAddress() { - return shippingAddress; + public PayerInfo setPhone(String phone) { + this.phone = phone; + return this; } /** - * Setter for shippingAddress; + * Getter for phone */ - public void setShippingAddress(Address shippingAddress) { - this.shippingAddress = shippingAddress; + public String getPhone() { + return this.phone; } + + /** - * Getter for phone + * Setter for shippingAddress */ - public String getPhone() { - return phone; + public PayerInfo setShippingAddress(Address shippingAddress) { + this.shippingAddress = shippingAddress; + return this; } /** - * Setter for phone; + * Getter for shippingAddress */ - public void setPhone(String phone) { - this.phone = phone; + public Address getShippingAddress() { + return this.shippingAddress; } - - - /** * Returns a JSON string corresponding to object state * @@ -136,10 +155,9 @@ public void setPhone(String phone) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payment.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payment.java index 76e469de..89ea9456 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Payment.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Payment.java @@ -1,73 +1,69 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Payer; -import java.util.List; import com.paypal.api.payments.Transaction; +import java.util.List; import com.paypal.api.payments.RedirectUrls; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; +import com.paypal.api.payments.Links; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.PayPalResource; import com.paypal.core.rest.HttpMethod; -import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.RESTUtil; import com.paypal.core.rest.QueryParameters; -import com.paypal.core.rest.JSONFormatter; import com.paypal.core.rest.APIContext; import java.io.File; import java.io.InputStream; import java.util.Properties; -import java.util.Map; - -/** - * - */ -public class Payment extends Resource { +public class Payment { /** - * - */ + * Identifier of the payment resource created. + */ private String id; - + /** - * - */ + * Time the resource was created. + */ private String createTime; - + /** - * - */ + * Time the resource was last updated. + */ private String updateTime; - - /** - * - */ - private String state; - + /** - * - */ + * Intent of the payment - Sale or Authorization or Order. + */ private String intent; - + /** - * - */ + * Source of the funds for this payment represented by a PayPal account or a direct credit card. + */ private Payer payer; - + /** - * - */ + * A payment can have more than one transaction, with each transaction establishing a contract between the payer and a payee + */ private List transactions; - + /** - * - */ + * state of the payment + */ + private String state; + + /** + * Redirect urls required only when using payment_method as PayPal - the only settings supported are return and cancel urls. + */ private RedirectUrls redirectUrls; - + /** * - */ - private List links; - + */ + private List links; + /** * Returns the last request sent to the Service * @@ -85,7 +81,7 @@ public static String getLastRequest() { public static String getLastResponse() { return PayPalResource.getLastResponse(); } - + /** * Initialize using InputStream(of a Properties file) * @@ -117,137 +113,294 @@ public static void initConfig(File file) throws PayPalRESTException { public static void initConfig(Properties properties) { PayPalResource.initConfig(properties); } - - /** - * Constructor + * Default Constructor */ public Payment() { - - } + } /** - * Getter for id + * Parameterized Constructor */ - public String getId() { - return id; + public Payment(String intent, Payer payer, List transactions) { + this.intent = intent; + this.payer = payer; + this.transactions = transactions; } + /** - * Setter for id; + * Setter for id */ - public void setId(String id) { + public Payment setId(String id) { this.id = id; + return this; } + /** - * Getter for createTime + * Getter for id */ - public String getCreateTime() { - return createTime; + public String getId() { + return this.id; } - + + /** - * Setter for createTime; + * Setter for createTime */ - public void setCreateTime(String createTime) { + public Payment setCreateTime(String createTime) { this.createTime = createTime; + return this; } + /** - * Getter for updateTime + * Getter for createTime */ - public String getUpdateTime() { - return updateTime; + public String getCreateTime() { + return this.createTime; } - + + /** - * Setter for updateTime; + * Setter for updateTime */ - public void setUpdateTime(String updateTime) { + public Payment setUpdateTime(String updateTime) { this.updateTime = updateTime; + return this; } + /** - * Getter for state + * Getter for updateTime */ - public String getState() { - return state; + public String getUpdateTime() { + return this.updateTime; } - + + /** - * Setter for state; + * Setter for intent */ - public void setState(String state) { - this.state = state; + public Payment setIntent(String intent) { + this.intent = intent; + return this; } + /** * Getter for intent */ public String getIntent() { - return intent; + return this.intent; } - + + /** - * Setter for intent; + * Setter for payer */ - public void setIntent(String intent) { - this.intent = intent; + public Payment setPayer(Payer payer) { + this.payer = payer; + return this; } + /** * Getter for payer */ public Payer getPayer() { - return payer; + return this.payer; } - + + /** - * Setter for payer; + * Setter for transactions */ - public void setPayer(Payer payer) { - this.payer = payer; + public Payment setTransactions(List transactions) { + this.transactions = transactions; + return this; } + /** * Getter for transactions */ public List getTransactions() { - return transactions; + return this.transactions; + } + + + /** + * Setter for state + */ + public Payment setState(String state) { + this.state = state; + return this; } /** - * Setter for transactions; + * Getter for state */ - public void setTransactions(List transactions) { - this.transactions = transactions; + public String getState() { + return this.state; } + + + /** + * Setter for redirectUrls + */ + public Payment setRedirectUrls(RedirectUrls redirectUrls) { + this.redirectUrls = redirectUrls; + return this; + } + /** * Getter for redirectUrls */ public RedirectUrls getRedirectUrls() { - return redirectUrls; + return this.redirectUrls; } - + + /** - * Setter for redirectUrls; + * Setter for links */ - public void setRedirectUrls(RedirectUrls redirectUrls) { - this.redirectUrls = redirectUrls; + public Payment setLinks(List links) { + this.links = links; + return this; } + /** * Getter for links */ - public List getLinks() { - return links; + public List getLinks() { + return this.links; + } + + + /** + * Creates (and processes) a new Payment Resource. + */ + public Payment create(String accessToken) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return create(apiContext); } /** - * Setter for links; + * Creates (and processes) a new Payment Resource. */ - public void setLinks(List links) { - this.links = links; + public Payment create(APIContext apiContext) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + String resourcePath = "v1/payments/payment"; + String payLoad = this.toJSON(); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Payment.class); } + + /** + * Obtain the Payment resource for the given identifier. + */ + public static Payment get(String accessToken, String paymentId) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, paymentId); + } + + /** + * Obtain the Payment resource for the given identifier. + */ + public static Payment get(APIContext apiContext, String paymentId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (paymentId == null) { + throw new IllegalArgumentException("paymentId cannot be null"); + } + Object[] parameters = new Object[] {paymentId}; + String pattern = "v1/payments/payment/{0}"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Payment.class); + } + + /** + * Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal. + */ + public Payment execute(String accessToken, PaymentExecution paymentExecution) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return execute(apiContext, paymentExecution); + } + + /** + * Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal. + */ + public Payment execute(APIContext apiContext, PaymentExecution paymentExecution) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (this.getId() == null) { + throw new IllegalArgumentException("Id cannot be null"); + } + if (paymentExecution == null) { + throw new IllegalArgumentException("paymentExecution cannot be null"); + } + Object[] parameters = new Object[] {this.getId()}; + String pattern = "v1/payments/payment/{0}/execute"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = paymentExecution.toJSON(); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Payment.class); + } + + /** + * Retrieves a list of Payment resources. + * @param containerMap + * Map containing the query strings with the + * following values as keys: + * count, + * start_id, + * start_index, + * start_time, + * end_time, + * payee_id, + * sort_by, + * sort_order, + * All other keys in the map are ignored by the SDK + */ + public static PaymentHistory list(String accessToken, Map containerMap) throws PayPalRESTException { + APIContext apiContext = new APIContext(accessToken); + return list(apiContext, containerMap); + } + + /** + * Retrieves a list of Payment resources. + * @param containerMap + * Map containing the query strings with the + * following values as keys: + * count, + * start_id, + * start_index, + * start_time, + * end_time, + * payee_id, + * sort_by, + * sort_order, + * All other keys in the map are ignored by the SDK + */ + public static PaymentHistory list(APIContext apiContext, Map containerMap) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (containerMap == null) { + throw new IllegalArgumentException("containerMap cannot be null"); + } + Object[] parameters = new Object[] {containerMap}; + String pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}"; + String resourcePath = RESTUtil.formatURIPath(pattern, parameters); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, PaymentHistory.class); + } + /** * Get call for Payment. + * @deprecated * @param accessToken * AccessToken used for the API call * @param containerMap @@ -267,116 +420,92 @@ public void setLinks(List links) { * @return PaymentHistory */ public static PaymentHistory get(String accessToken, Map containerMap) throws PayPalRESTException { - String pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}"; - Object[] parameters = new Object[] { containerMap }; - String resourcePath = RESTUtil.formatURIPath(pattern, parameters); - String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, PaymentHistory.class); + return list(accessToken, containerMap); } - /** * Get call for Payment. - * @param accessToken - * AccessToken used for the API call - * @param queryParameters - * Container for query strings + * @deprecated + * @param apiContext + * {@link APIContext} to be used for the call. + * @param containerMap + * Map containing the query strings with the + * following values as keys: + * count, + * start_id, + * start_index, + * start_time, + * end_time, + * payee_id, + * sort_by, + * sort_order, + * All other keys in the map are ignored by the SDK * @HttpMethod GET * @URIpath v1/payments/payment?count=:count&start_id=:start_id&start_index=:start_index&start_time=:start_time&end_time=:end_time&payee_id=:payee_id&sort_by=:sort_by&sort_order=:sort_order * @return PaymentHistory */ - public static PaymentHistory get(String accessToken, QueryParameters queryParameters) throws PayPalRESTException { - String pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}"; - Object[] parameters = new Object[] { queryParameters }; - String resourcePath = RESTUtil.formatURIPath(pattern, parameters); - String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, PaymentHistory.class); + public static PaymentHistory get(APIContext apiContext, Map containerMap) throws PayPalRESTException { + return list(apiContext, containerMap); } + /** - * Create call for Payment. + * Get call for Payment. + * @deprecated * @param accessToken * AccessToken used for the API call - * @HttpMethod POST - * @URIpath v1/payments/payment - * @return Payment + * @param queryParameters + * Container for query strings + * @HttpMethod GET + * @URIpath v1/payments/payment?count=:count&start_id=:start_id&start_index=:start_index&start_time=:start_time&end_time=:end_time&payee_id=:payee_id&sort_by=:sort_by&sort_order=:sort_order + * @return PaymentHistory */ - public Payment create(String accessToken) throws PayPalRESTException { - APIContext apiContext = new APIContext(accessToken); - return create(apiContext); + public static PaymentHistory get(String accessToken, QueryParameters queryParameters) throws PayPalRESTException { + return list(accessToken, queryParameters); } - /** - * Create call for Payment. - * @param apiContext - * APIContext used for the API call - * @HttpMethod POST - * @URIpath v1/payments/payment - * @return Payment - */ - public Payment create(APIContext apiContext) throws PayPalRESTException { - String resourcePath = "v1/payments/payment"; - String payLoad = this.toJSON(); - return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Payment.class); - } - /** * Get call for Payment. - * @param accessToken - * AccessToken used for the API call - * @param paymentId + * @deprecated + * @param apiContext + * {@link APIContext} to be used for the call. + * @param queryParameters + * Container for query strings * @HttpMethod GET - * @URIpath v1/payments/payment/:paymentId - * @return Payment + * @URIpath v1/payments/payment?count=:count&start_id=:start_id&start_index=:start_index&start_time=:start_time&end_time=:end_time&payee_id=:payee_id&sort_by=:sort_by&sort_order=:sort_order + * @return PaymentHistory */ - public static Payment get(String accessToken, String paymentId) throws PayPalRESTException { - if ((paymentId == null) || (paymentId.length() <= 0)) { - throw new IllegalArgumentException("paymentId cannot be null or empty"); - } - String pattern = "v1/payments/payment/{0}"; - Object[] parameters = new Object[] { paymentId }; - String resourcePath = RESTUtil.formatURIPath(pattern, parameters); - String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, Payment.class); + public static PaymentHistory get(APIContext apiContext, QueryParameters queryParameters) throws PayPalRESTException { + return list(apiContext, queryParameters); } - + /** - * Execute call for Payment. - * @param accessToken - * AccessToken used for the API call - * @param paymentExecution - * @HttpMethod POST - * @URIpath v1/payments/payment/:paymentId/execute - * @return Payment + * Retrieves a list of Payment resources. + * @deprecated */ - public Payment execute(String accessToken, PaymentExecution paymentExecution) throws PayPalRESTException { + public static PaymentHistory list(String accessToken, QueryParameters queryParameters) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); - return execute(apiContext, paymentExecution); + return list(apiContext, queryParameters); } /** - * Execute call for Payment. - * @param apiContext - * APIContext used for the API call - * @param paymentExecution - * @HttpMethod POST - * @URIpath v1/payments/payment/:paymentId/execute - * @return Payment + * Retrieves a list of Payment resources. + * @deprecated */ - public Payment execute(APIContext apiContext, PaymentExecution paymentExecution) throws PayPalRESTException { - if (paymentExecution == null) { - throw new IllegalArgumentException("paymentExecution cannot be null"); + public static PaymentHistory list(APIContext apiContext, QueryParameters queryParameters) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); } - if (this.getId() == null) { - throw new IllegalArgumentException("Id cannot be null"); + if (queryParameters == null) { + throw new IllegalArgumentException("queryParameters cannot be null"); } - String pattern = "v1/payments/payment/{0}/execute"; - Object[] parameters = new Object[] { this.getId() }; + Object[] parameters = new Object[] {queryParameters}; + String pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); - String payLoad = paymentExecution.toJSON(); - return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Payment.class); + String payLoad = ""; + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, PaymentHistory.class); } - + /** * Returns a JSON string corresponding to object state * @@ -385,10 +514,9 @@ public Payment execute(APIContext apiContext, PaymentExecution paymentExecution) public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentExecution.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentExecution.java index e42b3b3b..57052af7 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentExecution.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentExecution.java @@ -1,61 +1,75 @@ package com.paypal.api.payments; -import java.util.List; -import com.paypal.api.payments.Amount; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class PaymentExecution extends Resource { +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Transactions; +import java.util.List; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class PaymentExecution { /** - * - */ + * PayPal assigned Payer ID returned in the approval return url. + */ private String payerId; - + /** - * - */ - private List transactions; - + * If the amount needs to be updated after obtaining the PayPal Payer info (eg. shipping address), it can be updated using this element. + */ + private List transactions; + /** - * Constructor + * Default Constructor */ public PaymentExecution() { - - } + } /** - * Getter for payerId + * Parameterized Constructor */ - public String getPayerId() { - return payerId; + public PaymentExecution(String payerId) { + this.payerId = payerId; } + /** - * Setter for payerId; + * Setter for payerId */ - public void setPayerId(String payerId) { + public PaymentExecution setPayerId(String payerId) { this.payerId = payerId; + return this; } + /** - * Getter for transactions + * Getter for payerId */ - public List getTransactions() { - return transactions; + public String getPayerId() { + return this.payerId; } - + + /** - * Setter for transactions; + * Setter for transactions */ - public void setTransactions(List transactions) { + public PaymentExecution setTransactions(List transactions) { this.transactions = transactions; + return this; + } + + /** + * Getter for transactions + */ + public List getTransactions() { + return this.transactions; } - - - /** * Returns a JSON string corresponding to object state @@ -65,10 +79,9 @@ public void setTransactions(List transactions) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentHistory.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentHistory.java index 94e08fa2..1f5e969c 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentHistory.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/PaymentHistory.java @@ -1,80 +1,90 @@ package com.paypal.api.payments; -import java.util.List; -import com.paypal.api.payments.Payment; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class PaymentHistory extends Resource { +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Payment; +import java.util.List; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class PaymentHistory { /** - * - */ + * A list of Payment resources + */ private List payments; - + /** - * - */ - private Integer count; - + * Number of items returned in each range of results. Note that the last results range could have fewer items than the requested number of items. + */ + private int count; + /** - * - */ + * Identifier of the next element to get the next range of results. + */ private String nextId; - + /** - * Constructor + * Default Constructor */ public PaymentHistory() { + } - } /** - * Getter for payments + * Setter for payments */ - public List getPayments() { - return payments; + public PaymentHistory setPayments(List payments) { + this.payments = payments; + return this; } /** - * Setter for payments; + * Getter for payments */ - public void setPayments(List payments) { - this.payments = payments; + public List getPayments() { + return this.payments; } + + /** - * Getter for count + * Setter for count */ - public Integer getCount() { - return count; + public PaymentHistory setCount(int count) { + this.count = count; + return this; } /** - * Setter for count; + * Getter for count */ - public void setCount(Integer count) { - this.count = count; + public int getCount() { + return this.count; } + + /** - * Getter for nextId + * Setter for nextId */ - public String getNextId() { - return nextId; + public PaymentHistory setNextId(String nextId) { + this.nextId = nextId; + return this; } /** - * Setter for nextId; + * Getter for nextId */ - public void setNextId(String nextId) { - this.nextId = nextId; + public String getNextId() { + return this.nextId; } - - - /** * Returns a JSON string corresponding to object state * @@ -83,10 +93,9 @@ public void setNextId(String nextId) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/RedirectUrls.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/RedirectUrls.java index 5ba3cae9..58b01770 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/RedirectUrls.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/RedirectUrls.java @@ -1,60 +1,67 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; -/** - * - */ -public class RedirectUrls extends Resource { +import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class RedirectUrls { /** - * - */ + * Url where the payer would be redirected to after approving the payment. + */ private String returnUrl; - + /** - * - */ + * Url where the payer would be redirected to after canceling the payment. + */ private String cancelUrl; - + /** - * Constructor + * Default Constructor */ public RedirectUrls() { + } - } /** - * Getter for returnUrl + * Setter for returnUrl */ - public String getReturnUrl() { - return returnUrl; + public RedirectUrls setReturnUrl(String returnUrl) { + this.returnUrl = returnUrl; + return this; } /** - * Setter for returnUrl; + * Getter for returnUrl */ - public void setReturnUrl(String returnUrl) { - this.returnUrl = returnUrl; + public String getReturnUrl() { + return this.returnUrl; } + + /** - * Getter for cancelUrl + * Setter for cancelUrl */ - public String getCancelUrl() { - return cancelUrl; + public RedirectUrls setCancelUrl(String cancelUrl) { + this.cancelUrl = cancelUrl; + return this; } /** - * Setter for cancelUrl; + * Getter for cancelUrl */ - public void setCancelUrl(String cancelUrl) { - this.cancelUrl = cancelUrl; + public String getCancelUrl() { + return this.cancelUrl; } - - - /** * Returns a JSON string corresponding to object state * @@ -63,10 +70,9 @@ public void setCancelUrl(String cancelUrl) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Refund.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Refund.java index b8aaf2a7..a4649f84 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Refund.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Refund.java @@ -1,74 +1,62 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Links; import java.util.List; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.PayPalResource; import com.paypal.core.rest.HttpMethod; -import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.RESTUtil; -import com.paypal.core.rest.JSONFormatter; +import com.paypal.core.rest.QueryParameters; import com.paypal.core.rest.APIContext; import java.io.File; import java.io.InputStream; import java.util.Properties; -/** - * - */ -public class Refund extends Resource { - +public class Refund { /** - * - */ + * Identifier of the refund transaction. + */ private String id; - + /** - * - */ + * Time the resource was created. + */ private String createTime; - + /** - * - */ - private String updateTime; - + * Details including both refunded amount (to Payer) and refunded fee (to Payee).If amount is not specified, it's assumed to be full refund. + */ + private Amount amount; + /** - * - */ + * State of the refund transaction. + */ private String state; - - /** - * - */ - private Amount amount; - + /** - * - */ + * ID of the Sale transaction being refunded. + */ private String saleId; - + /** - * - */ + * ID of the Capture transaction being refunded. + */ private String captureId; - + /** - * - */ + * ID of the Payment resource that this transaction is based on. + */ private String parentPayment; - - /** - * - */ - private String description; - + /** * - */ - private List links; - + */ + private List links; + /** * Returns the last request sent to the Service * @@ -86,7 +74,7 @@ public static String getLastRequest() { public static String getLastResponse() { return PayPalResource.getLastResponse(); } - + /** * Initialize using InputStream(of a Properties file) * @@ -118,169 +106,166 @@ public static void initConfig(File file) throws PayPalRESTException { public static void initConfig(Properties properties) { PayPalResource.initConfig(properties); } - - /** - * Constructor + * Default Constructor */ public Refund() { + } - } /** - * Getter for id + * Setter for id */ - public String getId() { - return id; + public Refund setId(String id) { + this.id = id; + return this; } /** - * Setter for id; + * Getter for id */ - public void setId(String id) { - this.id = id; + public String getId() { + return this.id; } + + /** - * Getter for createTime + * Setter for createTime */ - public String getCreateTime() { - return createTime; + public Refund setCreateTime(String createTime) { + this.createTime = createTime; + return this; } /** - * Setter for createTime; + * Getter for createTime */ - public void setCreateTime(String createTime) { - this.createTime = createTime; + public String getCreateTime() { + return this.createTime; } + + /** - * Getter for updateTime + * Setter for amount */ - public String getUpdateTime() { - return updateTime; + public Refund setAmount(Amount amount) { + this.amount = amount; + return this; } /** - * Setter for updateTime; + * Getter for amount */ - public void setUpdateTime(String updateTime) { - this.updateTime = updateTime; + public Amount getAmount() { + return this.amount; } + + /** - * Getter for state + * Setter for state */ - public String getState() { - return state; + public Refund setState(String state) { + this.state = state; + return this; } /** - * Setter for state; + * Getter for state */ - public void setState(String state) { - this.state = state; + public String getState() { + return this.state; } + + /** - * Getter for amount + * Setter for saleId */ - public Amount getAmount() { - return amount; + public Refund setSaleId(String saleId) { + this.saleId = saleId; + return this; } - /** - * Setter for amount; - */ - public void setAmount(Amount amount) { - this.amount = amount; - } /** * Getter for saleId */ public String getSaleId() { - return saleId; + return this.saleId; } - + + /** - * Setter for saleId; + * Setter for captureId */ - public void setSaleId(String saleId) { - this.saleId = saleId; + public Refund setCaptureId(String captureId) { + this.captureId = captureId; + return this; } + /** * Getter for captureId */ public String getCaptureId() { - return captureId; + return this.captureId; } - + + /** - * Setter for captureId; + * Setter for parentPayment */ - public void setCaptureId(String captureId) { - this.captureId = captureId; + public Refund setParentPayment(String parentPayment) { + this.parentPayment = parentPayment; + return this; } + /** * Getter for parentPayment */ public String getParentPayment() { - return parentPayment; - } - - /** - * Setter for parentPayment; - */ - public void setParentPayment(String parentPayment) { - this.parentPayment = parentPayment; + return this.parentPayment; } + + /** - * Getter for description + * Setter for links */ - public String getDescription() { - return description; + public Refund setLinks(List links) { + this.links = links; + return this; } - /** - * Setter for description; - */ - public void setDescription(String description) { - this.description = description; - } /** * Getter for links */ - public List getLinks() { - return links; + public List getLinks() { + return this.links; } - - /** - * Setter for links; - */ - public void setLinks(List links) { - this.links = links; - } - - /** - * Get call for Refund. - * @param accessToken - * AccessToken used for the API call - * @param refundId - * @HttpMethod GET - * @URIpath v1/payments/refund/:refundId - * @return Refund + * Obtain the Refund transaction resource for the given identifier. */ public static Refund get(String accessToken, String refundId) throws PayPalRESTException { - if ((refundId == null) || (refundId.length() <= 0)) { - throw new IllegalArgumentException("refundId cannot be null or empty"); + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, refundId); + } + + /** + * Obtain the Refund transaction resource for the given identifier. + */ + public static Refund get(APIContext apiContext, String refundId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); + } + if (refundId == null) { + throw new IllegalArgumentException("refundId cannot be null"); } + Object[] parameters = new Object[] {refundId}; String pattern = "v1/payments/refund/{0}"; - Object[] parameters = new Object[] { refundId }; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, Refund.class); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Refund.class); } - + /** * Returns a JSON string corresponding to object state * @@ -289,10 +274,9 @@ public static Refund get(String accessToken, String refundId) throws PayPalRESTE public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/SubTransaction.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/RelatedResources.java similarity index 50% rename from rest-api-sdk/src/main/java/com/paypal/api/payments/SubTransaction.java rename to rest-api-sdk/src/main/java/com/paypal/api/payments/RelatedResources.java index 5528d7cc..8006cbdf 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/SubTransaction.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/RelatedResources.java @@ -1,100 +1,113 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Sale; import com.paypal.api.payments.Authorization; -import com.paypal.api.payments.Refund; import com.paypal.api.payments.Capture; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class SubTransaction extends Resource { +import com.paypal.api.payments.Refund; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class RelatedResources { /** - * - */ + * A sale transaction + */ private Sale sale; - + /** - * - */ + * An authorization transaction + */ private Authorization authorization; - - /** - * - */ - private Refund refund; - + /** - * - */ + * A capture transaction + */ private Capture capture; - + + /** + * A refund transaction + */ + private Refund refund; + /** - * Constructor + * Default Constructor */ - public SubTransaction() { + public RelatedResources() { + } - } /** - * Getter for sale + * Setter for sale */ - public Sale getSale() { - return sale; + public RelatedResources setSale(Sale sale) { + this.sale = sale; + return this; } /** - * Setter for sale; + * Getter for sale */ - public void setSale(Sale sale) { - this.sale = sale; + public Sale getSale() { + return this.sale; } + + /** - * Getter for authorization + * Setter for authorization */ - public Authorization getAuthorization() { - return authorization; + public RelatedResources setAuthorization(Authorization authorization) { + this.authorization = authorization; + return this; } /** - * Setter for authorization; + * Getter for authorization */ - public void setAuthorization(Authorization authorization) { - this.authorization = authorization; + public Authorization getAuthorization() { + return this.authorization; } + + /** - * Getter for refund + * Setter for capture */ - public Refund getRefund() { - return refund; + public RelatedResources setCapture(Capture capture) { + this.capture = capture; + return this; } /** - * Setter for refund; + * Getter for capture */ - public void setRefund(Refund refund) { - this.refund = refund; + public Capture getCapture() { + return this.capture; } + + /** - * Getter for capture + * Setter for refund */ - public Capture getCapture() { - return capture; + public RelatedResources setRefund(Refund refund) { + this.refund = refund; + return this; } /** - * Setter for capture; + * Getter for refund */ - public void setCapture(Capture capture) { - this.capture = capture; + public Refund getRefund() { + return this.refund; } - - - /** * Returns a JSON string corresponding to object state * @@ -103,10 +116,9 @@ public void setCapture(Capture capture) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Resource.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Resource.java deleted file mode 100644 index e9cc1d02..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Resource.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.paypal.api.payments; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class Resource{ - - - /** - * Constructor - */ - public Resource() { - - } - - - - - - /** - * Returns a JSON string corresponding to object state - * - * @return JSON representation - */ - public String toJSON() { - return JSONFormatter.toJSON(this); - } - - @Override - public String toString() { - return toJSON(); - } - -} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Sale.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Sale.java index 96c2a12e..8e362117 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Sale.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Sale.java @@ -1,59 +1,57 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Amount; +import com.paypal.api.payments.Links; import java.util.List; -import com.paypal.api.payments.Link; -import com.paypal.api.payments.Resource; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.PayPalResource; import com.paypal.core.rest.HttpMethod; -import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.RESTUtil; -import com.paypal.core.rest.JSONFormatter; +import com.paypal.core.rest.QueryParameters; import com.paypal.core.rest.APIContext; import java.io.File; import java.io.InputStream; import java.util.Properties; -/** - * - */ -public class Sale extends Resource { - +public class Sale { /** - * - */ + * Identifier of the authorization transaction. + */ private String id; - + /** - * - */ + * Time the resource was created. + */ private String createTime; - + /** - * - */ + * Time the resource was last updated. + */ private String updateTime; - - /** - * - */ - private String state; - + /** - * - */ + * Amount being collected. + */ private Amount amount; - + /** - * - */ + * State of the sale transaction. + */ + private String state; + + /** + * ID of the Payment resource that this transaction is based on. + */ private String parentPayment; - + /** * - */ - private List links; - + */ + private List links; + /** * Returns the last request sent to the Service * @@ -71,7 +69,7 @@ public static String getLastRequest() { public static String getLastResponse() { return PayPalResource.getLastResponse(); } - + /** * Initialize using InputStream(of a Properties file) * @@ -103,138 +101,162 @@ public static void initConfig(File file) throws PayPalRESTException { public static void initConfig(Properties properties) { PayPalResource.initConfig(properties); } - - /** - * Constructor + * Default Constructor */ public Sale() { - - } + } /** - * Getter for id + * Parameterized Constructor */ - public String getId() { - return id; + public Sale(Amount amount, String state, String parentPayment) { + this.amount = amount; + this.state = state; + this.parentPayment = parentPayment; } + /** - * Setter for id; + * Setter for id */ - public void setId(String id) { + public Sale setId(String id) { this.id = id; + return this; } + /** - * Getter for createTime + * Getter for id */ - public String getCreateTime() { - return createTime; + public String getId() { + return this.id; } - + + /** - * Setter for createTime; + * Setter for createTime */ - public void setCreateTime(String createTime) { + public Sale setCreateTime(String createTime) { this.createTime = createTime; + return this; } + /** - * Getter for updateTime + * Getter for createTime */ - public String getUpdateTime() { - return updateTime; + public String getCreateTime() { + return this.createTime; } - + + /** - * Setter for updateTime; + * Setter for updateTime */ - public void setUpdateTime(String updateTime) { + public Sale setUpdateTime(String updateTime) { this.updateTime = updateTime; + return this; } + /** - * Getter for state + * Getter for updateTime */ - public String getState() { - return state; + public String getUpdateTime() { + return this.updateTime; } - + + /** - * Setter for state; + * Setter for amount */ - public void setState(String state) { - this.state = state; + public Sale setAmount(Amount amount) { + this.amount = amount; + return this; } + /** * Getter for amount */ public Amount getAmount() { - return amount; + return this.amount; + } + + + /** + * Setter for state + */ + public Sale setState(String state) { + this.state = state; + return this; } /** - * Setter for amount; + * Getter for state */ - public void setAmount(Amount amount) { - this.amount = amount; + public String getState() { + return this.state; } + + /** - * Getter for parentPayment + * Setter for parentPayment */ - public String getParentPayment() { - return parentPayment; + public Sale setParentPayment(String parentPayment) { + this.parentPayment = parentPayment; + return this; } /** - * Setter for parentPayment; + * Getter for parentPayment */ - public void setParentPayment(String parentPayment) { - this.parentPayment = parentPayment; + public String getParentPayment() { + return this.parentPayment; } + + /** - * Getter for links + * Setter for links */ - public List getLinks() { - return links; + public Sale setLinks(List links) { + this.links = links; + return this; } /** - * Setter for links; + * Getter for links */ - public void setLinks(List links) { - this.links = links; + public List getLinks() { + return this.links; } - - /** - * Get call for Sale. - * @param accessToken - * AccessToken used for the API call - * @param saleId - * @HttpMethod GET - * @URIpath v1/payments/sale/:saleId - * @return Sale + * Obtain the Sale transaction resource for the given identifier. */ public static Sale get(String accessToken, String saleId) throws PayPalRESTException { - if ((saleId == null) || (saleId.length() <= 0)) { - throw new IllegalArgumentException("saleId cannot be null or empty"); + APIContext apiContext = new APIContext(accessToken); + return get(apiContext, saleId); + } + + /** + * Obtain the Sale transaction resource for the given identifier. + */ + public static Sale get(APIContext apiContext, String saleId) throws PayPalRESTException { + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); } + if (saleId == null) { + throw new IllegalArgumentException("saleId cannot be null"); + } + Object[] parameters = new Object[] {saleId}; String pattern = "v1/payments/sale/{0}"; - Object[] parameters = new Object[] { saleId }; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; - return PayPalResource.configureAndExecute(accessToken, HttpMethod.GET, resourcePath, payLoad, Sale.class); + return PayPalResource.configureAndExecute(apiContext, HttpMethod.GET, resourcePath, payLoad, Sale.class); } + /** - * Refund call for Sale. - * @param accessToken - * AccessToken used for the API call - * @param refund - * @HttpMethod POST - * @URIpath v1/payments/sale/:saleId/refund - * @return Refund + * Creates (and processes) a new Refund Transaction added as a related resource. */ public Refund refund(String accessToken, Refund refund) throws PayPalRESTException { APIContext apiContext = new APIContext(accessToken); @@ -242,28 +264,25 @@ public Refund refund(String accessToken, Refund refund) throws PayPalRESTExcepti } /** - * Refund call for Sale. - * @param apiContext - * APIContext used for the API call - * @param refund - * @HttpMethod POST - * @URIpath v1/payments/sale/:saleId/refund - * @return Refund + * Creates (and processes) a new Refund Transaction added as a related resource. */ public Refund refund(APIContext apiContext, Refund refund) throws PayPalRESTException { - if (refund == null) { - throw new IllegalArgumentException("refund cannot be null"); + if (apiContext.getAccessToken() == null || apiContext.getAccessToken().trim().length() <= 0) { + throw new IllegalArgumentException("AccessToken cannot be null or empty"); } if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } + if (refund == null) { + throw new IllegalArgumentException("refund cannot be null"); + } + Object[] parameters = new Object[] {this.getId()}; String pattern = "v1/payments/sale/{0}/refund"; - Object[] parameters = new Object[] { this.getId() }; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); - String payLoad = refund.toJSON(); + String payLoad = refund.toJSON(); return PayPalResource.configureAndExecute(apiContext, HttpMethod.POST, resourcePath, payLoad, Refund.class); } - + /** * Returns a JSON string corresponding to object state * @@ -272,10 +291,9 @@ public Refund refund(APIContext apiContext, Refund refund) throws PayPalRESTExce public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/ShippingAddress.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/ShippingAddress.java index bf874b67..1ff3e802 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/ShippingAddress.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/ShippingAddress.java @@ -1,41 +1,53 @@ package com.paypal.api.payments; -import com.paypal.api.payments.Address; + import com.paypal.core.rest.JSONFormatter; +import java.util.Map; +import com.paypal.api.payments.Address; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; -/** - * - */ public class ShippingAddress extends Address { - /** - * - */ + * Name of the recipient at this address. + */ private String recipientName; - + /** - * Constructor + * Default Constructor */ public ShippingAddress() { - - } + } /** - * Getter for recipientName + * Parameterized Constructor */ - public String getRecipientName() { - return recipientName; + public ShippingAddress(String recipientName) { + this.recipientName = recipientName; } + /** - * Setter for recipientName; + * Setter for recipientName */ - public void setRecipientName(String recipientName) { + public ShippingAddress setRecipientName(String recipientName) { this.recipientName = recipientName; + return this; + } + + /** + * Getter for recipientName + */ + public String getRecipientName() { + return this.recipientName; } - - - /** * Returns a JSON string corresponding to object state @@ -45,10 +57,9 @@ public void setRecipientName(String recipientName) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Transaction.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Transaction.java index 92357740..2f41c9a3 100644 --- a/rest-api-sdk/src/main/java/com/paypal/api/payments/Transaction.java +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Transaction.java @@ -1,119 +1,163 @@ package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; import com.paypal.api.payments.Amount; import com.paypal.api.payments.Payee; import com.paypal.api.payments.ItemList; +import com.paypal.api.payments.RelatedResources; import java.util.List; -import com.paypal.api.payments.SubTransaction; -import com.paypal.api.payments.Resource; -import com.paypal.core.rest.JSONFormatter; - -/** - * - */ -public class Transaction extends Resource { +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +public class Transaction { /** - * - */ + * Amount being collected. + */ private Amount amount; - + /** - * - */ + * Recepient of the funds in this transaction. + */ private Payee payee; - + /** - * - */ + * Description of what is being paid for. + */ private String description; - + /** - * - */ + * List of items being paid for. + */ private ItemList itemList; - + /** - * - */ - private List relatedResources; - + * List of financial transactions (Sale, Authorization, Capture, Refund) related to the payment. + */ + private List relatedResources; + /** - * Constructor + * Additional transactions for complex payment (Parallel and Chained) scenarios. + */ + private List transactions; + + /** + * Default Constructor */ public Transaction() { + } - } + /** + * Parameterized Constructor + */ + public Transaction(Amount amount) { + this.amount = amount; + } + + /** + * Setter for amount + */ + public Transaction setAmount(Amount amount) { + this.amount = amount; + return this; + } + /** * Getter for amount */ public Amount getAmount() { - return amount; + return this.amount; } - + + /** - * Setter for amount; + * Setter for payee */ - public void setAmount(Amount amount) { - this.amount = amount; + public Transaction setPayee(Payee payee) { + this.payee = payee; + return this; } + /** * Getter for payee */ public Payee getPayee() { - return payee; + return this.payee; } - + + /** - * Setter for payee; + * Setter for description */ - public void setPayee(Payee payee) { - this.payee = payee; + public Transaction setDescription(String description) { + this.description = description; + return this; } + /** * Getter for description */ public String getDescription() { - return description; + return this.description; } - + + /** - * Setter for description; + * Setter for itemList */ - public void setDescription(String description) { - this.description = description; + public Transaction setItemList(ItemList itemList) { + this.itemList = itemList; + return this; } + /** * Getter for itemList */ public ItemList getItemList() { - return itemList; + return this.itemList; } - + + /** - * Setter for itemList; + * Setter for relatedResources */ - public void setItemList(ItemList itemList) { - this.itemList = itemList; + public Transaction setRelatedResources(List relatedResources) { + this.relatedResources = relatedResources; + return this; } + /** * Getter for relatedResources */ - public List getRelatedResources() { - return relatedResources; + public List getRelatedResources() { + return this.relatedResources; + } + + + /** + * Setter for transactions + */ + public Transaction setTransactions(List transactions) { + this.transactions = transactions; + return this; } /** - * Setter for relatedResources; + * Getter for transactions */ - public void setRelatedResources(List relatedResources) { - this.relatedResources = relatedResources; + public List getTransactions() { + return this.transactions; } - - - /** * Returns a JSON string corresponding to object state * @@ -122,10 +166,9 @@ public void setRelatedResources(List relatedResources) { public String toJSON() { return JSONFormatter.toJSON(this); } - + @Override public String toString() { return toJSON(); } - } \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/api/payments/Transactions.java b/rest-api-sdk/src/main/java/com/paypal/api/payments/Transactions.java new file mode 100644 index 00000000..f1badb49 --- /dev/null +++ b/rest-api-sdk/src/main/java/com/paypal/api/payments/Transactions.java @@ -0,0 +1,65 @@ +package com.paypal.api.payments; + +import com.paypal.core.rest.JSONFormatter; +import com.paypal.api.payments.Amount; +import java.util.Map; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; +import com.paypal.core.rest.HttpMethod; +import com.paypal.core.rest.RESTUtil; +import com.paypal.core.rest.QueryParameters; +import com.paypal.core.rest.APIContext; +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +public class Transactions { + + /** + * Amount being collected. + */ + private Amount amount; + + /** + * Default Constructor + */ + public Transactions() { + } + + /** + * Parameterized Constructor + */ + public Transactions(Amount amount) { + this.amount = amount; + } + + + /** + * Setter for amount + */ + public Transactions setAmount(Amount amount) { + this.amount = amount; + return this; + } + + /** + * Getter for amount + */ + public Amount getAmount() { + return this.amount; + } + + /** + * Returns a JSON string corresponding to object state + * + * @return JSON representation + */ + public String toJSON() { + return JSONFormatter.toJSON(this); + } + + @Override + public String toString() { + return toJSON(); + } +} \ No newline at end of file diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/APIContext.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/APIContext.java deleted file mode 100644 index 115bf596..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/APIContext.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.paypal.core.rest; - -import java.util.UUID; - -/** - * APIContext holds wire-level parameters for the API call. - * AccessToken is treated as a mandatory parameter. RequestId is generated if - * not supplied - * - * @author kjayakumar - * - */ -public class APIContext { - - /** - * Access Token - */ - private String accessToken; - - /** - * Request Id - */ - private String requestId; - - /** - * APIContext - * - * @param accessToken - * AccessToken required for the call. - */ - public APIContext(String accessToken) { - if (accessToken == null || accessToken.length() <= 0) { - throw new IllegalArgumentException("AccessToken cannot be null"); - } - this.accessToken = accessToken; - } - - /** - * APIContext - * - * @param accessToken - * AccessToken required for the call. - * @param requestId - * Unique requestId required for the call. - */ - public APIContext(String accessToken, String requestId) { - this(accessToken); - if (requestId == null || requestId.length() <= 0) { - throw new IllegalArgumentException("RequestId cannot be null"); - } - this.requestId = requestId; - } - - /** - * Returns the Access Token - * - * @return Access Token - */ - public String getAccessToken() { - return accessToken; - } - - /** - * Returns the unique requestId set during creation, if not available - * returns a generated one - * - * @return requestId - */ - public String getRequestId() { - if (requestId == null || requestId.length() <= 0) { - requestId = UUID.randomUUID().toString(); - } - return requestId; - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/HttpMethod.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/HttpMethod.java deleted file mode 100644 index 5d54ed2c..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/HttpMethod.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.paypal.core.rest; - -/** - * HttpMethod enums used for HTTP method verbs - * @author kjayakumar - * - */ -public enum HttpMethod { - - // Get Http Method - GET, - - // Post Http Method - POST, - - // Patch Http Method - PATCH, - - // Put Http Method - PUT, - - // Delete Http Method - DELETE; - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/JSONFormatter.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/JSONFormatter.java deleted file mode 100644 index 7e85c59d..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/JSONFormatter.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.paypal.core.rest; - -import com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -/** - * JSONFormatter converts objects to JSON representation and vice-versa - * - * @author kjayakumar - * - */ -public class JSONFormatter { - - /** - * Gson - */ - public static final Gson GSON = new GsonBuilder() - .setPrettyPrinting() - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .create(); - - /** - * Converts a Raw Type to JSON String - * - * @param - * Type to be converted - * @param t - * Object of the type - * @return JSON representation - */ - public static String toJSON(T t) { - return GSON.toJson(t); - } - - /** - * Converts a JSON String to object representation - * - * @param - * Type to be converted - * @param responseString - * JSON representation - * @param clazz - * Target class - * @return Object of the target type - */ - public static T fromJSON(String responseString, Class clazz) { - T t = null; - t = GSON.fromJson(responseString, clazz); - return t; - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/OAuthTokenCredential.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/OAuthTokenCredential.java deleted file mode 100644 index dccac68f..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/OAuthTokenCredential.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.paypal.core.rest; - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.codec.binary.Base64; - -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.paypal.core.ConfigManager; -import com.paypal.core.ConnectionManager; -import com.paypal.core.Constants; -import com.paypal.core.HttpConfiguration; -import com.paypal.core.HttpConnection; -import com.paypal.core.credential.ICredential; - -public final class OAuthTokenCredential implements ICredential { - - private static final String OAUTH_TOKEN_PATH = "/v1/oauth2/token"; - - /** - * Client ID for OAuth - */ - private String clientID; - - /** - * Client Secret for OAuth - */ - private String clientSecret; - - /** - * Access Token that is generated - */ - private String accessToken; - - /** - * Application ID returned by OAuth servers - */ - private transient String appId; - - /** - * @param clientID - * Client ID for the OAuth - * @param clientSecret - * Client Secret for OAuth - */ - public OAuthTokenCredential(String clientID, String clientSecret) { - super(); - this.clientID = clientID; - this.clientSecret = clientSecret; - } - - /** - * Computes Access Token by placing a call to OAuth server - * using ClientID and ClientSecret. The token is appended - * to the token type. - * @return the accessToken - * @throws PayPalRESTException - */ - public String getAccessToken() throws PayPalRESTException { - if (accessToken == null) { - // Write Logic for passing in Detail to Identity Api Serv and - // computing the token - // Set the Value inside the accessToken and result - accessToken = generateAccessToken(); - } - return accessToken; - } - - private String generateAccessToken() throws PayPalRESTException { - String generatedToken = null; - String base64ClientID = generateBase64String(clientID + ":" + clientSecret); - generatedToken = generateOAuthToken(base64ClientID); - return generatedToken; - } - - /* - * Generate a Base64 encoded String from clientID & clientSecret - */ - private String generateBase64String(String clientID) - throws PayPalRESTException { - String base64ClientID = null; - byte[] encoded = null; - try { - encoded = Base64.encodeBase64(clientID.getBytes("UTF-8")); - base64ClientID = new String(encoded, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new PayPalRESTException(e.getMessage(), e); - } - return base64ClientID; - } - - /* - * Generate OAuth type token from Base64Client ID - */ - private String generateOAuthToken(String base64ClientID) - throws PayPalRESTException { - HttpConnection connection = null; - HttpConfiguration httpConfiguration = null; - String generatedToken = null; - try { - connection = ConnectionManager.getInstance().getConnection(); - httpConfiguration = getOAuthHttpConfiguration(); - connection.createAndconfigureHttpConnection(httpConfiguration); - Map headers = new HashMap(); - headers.put("Authorization", "Basic " + base64ClientID); - headers.put(Constants.HTTP_ACCEPT_HEADER, "*/*"); - String postRequest = "grant_type=client_credentials"; - String jsonResponse = connection.execute("", postRequest, headers); - JsonParser parser = new JsonParser(); - JsonElement jsonElement = parser.parse(jsonResponse); - generatedToken = jsonElement.getAsJsonObject().get("token_type") - .getAsString() - + " " - + jsonElement.getAsJsonObject().get("access_token") - .getAsString(); - appId = jsonElement.getAsJsonObject().get("app_id").getAsString(); - } catch (Exception e) { - throw new PayPalRESTException(e.getMessage(), e); - } - return generatedToken; - } - - /* - * Get HttpConfiguration object for OAuth server - */ - private HttpConfiguration getOAuthHttpConfiguration() { - ConfigManager config = ConfigManager.getInstance(); - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setHttpMethod("POST"); - String endPointUrl = config.getValue("service.EndPoint") + OAUTH_TOKEN_PATH; - httpConfiguration.setEndPointUrl(endPointUrl); - httpConfiguration.setGoogleAppEngine(Boolean.parseBoolean(config - .getValue(Constants.GOOGLE_APP_ENGINE))); - return httpConfiguration; - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalRESTException.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalRESTException.java deleted file mode 100644 index 0a1dc130..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalRESTException.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.paypal.core.rest; - -/** - * PayPalException handles all exceptions related to REST services - */ -public class PayPalRESTException extends Exception { - - public PayPalRESTException(String message) { - super(message); - } - - public PayPalRESTException(String message, Throwable throwable) { - super(message, throwable); - } - - public PayPalRESTException(Throwable throwable) { - super(throwable); - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalResource.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalResource.java deleted file mode 100644 index 5aa381b9..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/PayPalResource.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.paypal.core.rest; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.Properties; - -import com.paypal.core.ConfigManager; -import com.paypal.core.ConnectionManager; -import com.paypal.core.HttpConfiguration; -import com.paypal.core.HttpConnection; -import com.paypal.core.LoggingManager; - -/** - * PayPalResource acts as a base class for REST enabled resources - */ -public abstract class PayPalResource { - - /** - * SDK ID used in User-Agent HTTP header - */ - public static final String SDK_ID = "ID"; - - /** - * SDK Version used in User-Agent HTTP header - */ - public static final String SDK_VERSION = "0.5.2"; - - /** - * Configuration enabled flag - */ - private static boolean configInitialized = false; - - /** - * Last request sent to Service - */ - private static final ThreadLocal LASTREQUEST = new ThreadLocal(); - - /** - * Last response returned form Service - */ - private static final ThreadLocal LASTRESPONSE = new ThreadLocal(); - - /** - * Initialize using InputStream(of a Properties file) - * - * @param is - * InputStream - * @throws PayPalRESTException - */ - public static void initConfig(InputStream is) throws PayPalRESTException { - try { - ConfigManager.getInstance().load(is); - configInitialized = true; - } catch (IOException ioe) { - LoggingManager.severe(PayPalResource.class, ioe.getMessage(), ioe); - throw new PayPalRESTException(ioe.getMessage(), ioe); - } - - } - - /** - * Initialize using a File(Properties file) - * - * @param file - * File object of a properties entity - * @throws PayPalRESTException - */ - public static void initConfig(File file) throws PayPalRESTException { - try { - if (!file.exists()) { - throw new FileNotFoundException("File doesn't exist: " - + file.getAbsolutePath()); - } - FileInputStream fis = new FileInputStream(file); - initConfig(fis); - configInitialized = true; - } catch (IOException ioe) { - LoggingManager.severe(PayPalResource.class, ioe.getMessage(), ioe); - throw new PayPalRESTException(ioe.getMessage(), ioe); - } - - } - - /** - * Initialize using Properties - * - * @param properties - * Properties object - */ - public static void initConfig(Properties properties) { - ConfigManager.getInstance().load(properties); - configInitialized = true; - } - - /** - * Initialize to default properties - * - * @throws PayPalRESTException - */ - private static void initializeToDefault() throws PayPalRESTException { - initConfig(PayPalResource.class.getClassLoader().getResourceAsStream( - "sdk_config.properties")); - } - - /** - * Returns the last request sent to the Service - * - * @return Last request sent to the server - */ - public static String getLastRequest() { - return LASTREQUEST.get(); - } - - /** - * Returns the last response returned by the Service - * - * @return Last response got from the Service - */ - public static String getLastResponse() { - return LASTRESPONSE.get(); - } - - /** - * Configures and executes REST call: Supports JSON - * - * @param - * Response Type for de-serialization - * @param accessToken - * AccessToken to be used for the call. - * @param httpMethod - * Http Method verb - * @param resource - * Resource URI path - * @param payLoad - * Payload to Service - * @param clazz - * {@link Class} object used in De-serialization - * @return - * @throws PayPalRESTException - */ - public static T configureAndExecute(String accessToken, - HttpMethod httpMethod, String resourcePath, String payLoad, - Class clazz) throws PayPalRESTException { - T t = null; - if (!configInitialized) { - initializeToDefault(); - } - RESTConfiguration restConfiguration = createRESTConfiguration( - httpMethod, resourcePath, accessToken, null); - - t = execute(restConfiguration, payLoad, resourcePath, clazz); - return t; - } - - /** - * Configures and executes REST call: Supports JSON - * - * @param - * Response Type for de-serialization - * @param apiContext - * {@link APIContext} to be used for the call. - * @param httpMethod - * Http Method verb - * @param resource - * Resource URI path - * @param payLoad - * Payload to Service - * @param clazz - * {@link Class} object used in De-serialization - * @return - * @throws PayPalRESTException - */ - public static T configureAndExecute(APIContext apiContext, - HttpMethod httpMethod, String resourcePath, String payLoad, - Class clazz) throws PayPalRESTException { - T t = null; - if (!configInitialized) { - initializeToDefault(); - } - RESTConfiguration restConfiguration = createRESTConfiguration( - httpMethod, resourcePath, apiContext.getAccessToken(), - apiContext.getRequestId()); - - t = execute(restConfiguration, payLoad, resourcePath, clazz); - return t; - } - - /** - * Creates a {@link RESTConfiguration} based on configuration - * - * @param httpMethod - * {@link HttpMethod} - * @param resourcePath - * Resource URI - * @param accessToken - * Access Token - * @param requestId - * Request Id - * @return - */ - private static RESTConfiguration createRESTConfiguration( - HttpMethod httpMethod, String resourcePath, String accessToken, - String requestId) { - RESTConfiguration restConfiguration = new RESTConfiguration(); - restConfiguration.setHttpMethod(httpMethod); - restConfiguration.setResourcePath(resourcePath); - restConfiguration.setRequestId(requestId); - restConfiguration.setAuthorizationToken(accessToken); - return restConfiguration; - } - - /** - * Execute the API call and return response - * - * @param - * Type of the return object - * @param restConfiguration - * {@link RESTConfiguration} - * @param payLoad - * Payload - * @param resourcePath - * Resource URI - * @param clazz - * Class of the return object - * @return API response type object - * @throws PayPalRESTException - */ - private static T execute(RESTConfiguration restConfiguration, - String payLoad, String resourcePath, Class clazz) - throws PayPalRESTException { - T t = null; - ConnectionManager connectionManager; - HttpConnection httpConnection; - HttpConfiguration httpConfig; - Map headers; - String responseString; - try { - - // REST Headers - headers = restConfiguration.getHeaders(); - - // HTTPConfiguration Object - httpConfig = restConfiguration.getHttpConfigurations(); - - // HttpConnection Initialization - connectionManager = ConnectionManager.getInstance(); - httpConnection = connectionManager.getConnection(httpConfig); - httpConnection.createAndconfigureHttpConnection(httpConfig); - - LASTREQUEST.set(payLoad); - responseString = httpConnection.execute(restConfiguration - .getBaseURL().toURI().resolve(resourcePath).toString(), - payLoad, headers); - LASTRESPONSE.set(responseString); - t = JSONFormatter.fromJSON(responseString, clazz); - } catch (Exception e) { - throw new PayPalRESTException(e.getMessage(), e); - } - return t; - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/QueryParameters.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/QueryParameters.java deleted file mode 100644 index 1495c27c..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/QueryParameters.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.paypal.core.rest; - -import java.util.HashMap; -import java.util.Map; - -import com.paypal.api.payments.PaymentHistory; - -/** - * QueryParameters holds query parameters used for retrieving - * {@link PaymentHistory} object. - * - * @author kjayakumar - * - */ -public class QueryParameters { - - /** - * Count - */ - private static final String COUNT = "count"; - - /** - * Start Id - */ - private static final String STARTID = "start_id"; - - /** - * Start Index - */ - private static final String STARTINDEX = "start_index"; - - /** - * Start Time - */ - private static final String STARTTIME = "start_time"; - - /** - * End Time - */ - private static final String ENDTIME = "end_time"; - - /** - * Payee Id - */ - private static final String PAYEEID = "payee_id"; - - /** - * Sort By - */ - private static final String SORTBY = "sort_by"; - - /** - * Sort Order - */ - private static final String SORTORDER = "sort_order"; - - // Map backing QueryParameters intended to processed - // by SDK library 'RESTUtil' - private Map containerMap; - - public QueryParameters() { - containerMap = new HashMap(); - } - - /** - * @return the containerMap - */ - Map getContainerMap() { - return containerMap; - } - - /** - * Set the count - * - * @param count - * Number of items to return. - */ - public void setCount(String count) { - containerMap.put(COUNT, count); - } - - /** - * Set the startId - * - * @param startId - * Resource ID that indicates the starting resource to return. - */ - public void setStartId(String startId) { - containerMap.put(STARTID, startId); - } - - /** - * Set the startIndex - * - * @param startIndex - * Start index of the resources to be returned. Typically used to - * jump to a specific position in the resource history based on - * its order. - */ - public void setStartIndex(String startIndex) { - containerMap.put(STARTINDEX, startIndex); - } - - /** - * Set the startTime - * - * @param startTime - * Resource creation time that indicates the start of a range of - * results. - */ - public void setStartTime(String startTime) { - containerMap.put(STARTTIME, startTime); - } - - /** - * Set the endTime - * - * @param endTime - * Resource creation time that indicates the end of a range of - * results. - */ - public void setEndTime(String endTime) { - containerMap.put(ENDTIME, endTime); - } - - /** - * Set the payeeId - * - * @param payeeId - * PayeeId - */ - public void setPayeeId(String payeeId) { - containerMap.put(PAYEEID, payeeId); - } - - /** - * Set the sortBy - * - * @param sortBy - * Sort based on create_time or update_time. - */ - public void setSortBy(String sortBy) { - containerMap.put(SORTBY, sortBy); - } - - /** - * Set the sortOrder - * - * @param sortOrder - * Sort based on order of results. Options include asc for - * ascending order or dec for descending order. - */ - public void setSortOrder(String sortOrder) { - containerMap.put(SORTORDER, sortOrder); - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTConfiguration.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTConfiguration.java deleted file mode 100644 index f6332a8b..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTConfiguration.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.paypal.core.rest; - -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import com.paypal.core.ConfigManager; -import com.paypal.core.Constants; -import com.paypal.core.HttpConfiguration; - -/** - * RESTConfiguration helps {@link PayPalResource} with state dependent utility - * methods - */ -public class RESTConfiguration { - - /** - * Java Version and bit header computed during construction - */ - private static final String JAVAHEADER; - - /** - * OS Version and bit header computed during construction - */ - private static final String OSHEADER; - - static { - - // Java Version computed statically - StringBuilder javaVersion = new StringBuilder("lang=Java"); - if (System.getProperty("java.version") != null - && System.getProperty("java.version").length() > 0) { - javaVersion.append(";V=") - .append(System.getProperty("java.version")); - } - if (System.getProperty("java.vm.name") != null - && System.getProperty("java.vm.name").length() > 0) { - javaVersion.append(";b="); - if (System.getProperty("java.vm.name").contains("Client")) { - javaVersion.append("32"); - } else { - javaVersion.append("64"); - } - } - JAVAHEADER = javaVersion.toString(); - - // OS Version Header - StringBuilder osVersion = new StringBuilder(); - if (System.getProperty("os.name") != null - && System.getProperty("os.name").length() > 0) { - osVersion.append("OS="); - osVersion.append(System.getProperty("os.name").replace(' ', '_')); - } else { - osVersion.append("OS="); - } - if (System.getProperty("os.version") != null - && System.getProperty("os.version").length() > 0) { - osVersion.append(" " - + System.getProperty("os.version").replace(' ', '_')); - } - OSHEADER = osVersion.toString(); - } - - /** - * Base URL for the service - */ - private URL url; - - /** - * Authorization token - */ - private String authorizationToken; - - /** - * {@link HttpMethod} - */ - private HttpMethod httpMethod; - - /** - * Resource URI as defined in the WSDL - */ - private String resourcePath; - - /** - * Request Id - */ - private String requestId; - - /** - * Default Constructor - */ - public RESTConfiguration() { - - } - - /** - * @param authorizationToken - * the authorizationToken to set - */ - public void setAuthorizationToken(String authorizationToken) { - this.authorizationToken = authorizationToken; - } - - /** - * @param httpMethod - * the httpMethod to set - */ - public void setHttpMethod(HttpMethod httpMethod) { - this.httpMethod = httpMethod; - } - - /** - * @param resourcePath - * the resourcePath to set - */ - public void setResourcePath(String resourcePath) { - this.resourcePath = resourcePath; - } - - /** - * @param requestId - * the requestId to set - */ - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - /** - * Returns HTTP headers as a {@link Map} - * - * @return {@link Map} of Http headers - */ - public Map getHeaders() { - Map headers = new HashMap(); - headers.put("Authorization", authorizationToken); - headers.put("User-Agent", formUserAgentHeader()); - if (requestId != null && requestId.length() > 0) { - headers.put("PayPal-Request-Id", requestId); - } - return headers; - } - - /** - * Returns a {@link HttpConfiguration} based on configuration - * - * @return {@link HttpConfiguration} - * @throws MalformedURLException - * @throws URISyntaxException - */ - public HttpConfiguration getHttpConfigurations() - throws MalformedURLException, URISyntaxException { - ConfigManager config = ConfigManager.getInstance(); - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setHttpMethod(httpMethod.toString()); - httpConfiguration.setEndPointUrl(getBaseURL().toURI() - .resolve(resourcePath).toString()); - httpConfiguration.setContentType("application/json"); - httpConfiguration.setGoogleAppEngine(Boolean.parseBoolean(config - .getValue(Constants.GOOGLE_APP_ENGINE))); - if (Boolean.parseBoolean(config.getValue(Constants.USE_HTTP_PROXY))) { - httpConfiguration.setProxyPort(Integer.parseInt(config - .getValue(Constants.HTTP_PROXY_PORT))); - httpConfiguration.setProxyHost(config - .getValue(Constants.HTTP_PROXY_HOST)); - httpConfiguration.setProxyUserName(config - .getValue(Constants.HTTP_PROXY_USERNAME)); - httpConfiguration.setProxyPassword(config - .getValue(Constants.HTTP_PROXY_PASSWORD)); - } - httpConfiguration.setConnectionTimeout(Integer.parseInt(config - .getValue(Constants.HTTP_CONNECTION_TIMEOUT))); - httpConfiguration.setMaxRetry(Integer.parseInt(config - .getValue(Constants.HTTP_CONNECTION_RETRY))); - httpConfiguration.setReadTimeout(Integer.parseInt(config - .getValue(Constants.HTTP_CONNECTION_READ_TIMEOUT))); - httpConfiguration.setMaxHttpConnection(Integer.parseInt(config - .getValue(Constants.HTTP_CONNECTION_MAX_CONNECTION))); - httpConfiguration.setIpAddress(config - .getValue(Constants.DEVICE_IP_ADDRESS)); - return httpConfiguration; - } - - /** - * Returns the base URL configured in application resources - * - * @return Base {@link URL} - * @throws MalformedURLException - */ - public URL getBaseURL() throws MalformedURLException { - if (url == null) { - String urlString = ConfigManager.getInstance().getValue( - "service.EndPoint"); - if (!urlString.endsWith("/")) { - urlString += "/"; - } - url = new URL(urlString); - } - return url; - } - - /** - * @param urlString - * the url to set - */ - public void setUrl(String urlString) throws MalformedURLException { - if (urlString != null && urlString.length() > 0) { - if (!urlString.endsWith("/")) { - urlString += "/"; - } - this.url = new URL(urlString); - } else { - this.url = getBaseURL(); - } - } - - /* - * Form User-Agent HTTP header - */ - private String formUserAgentHeader() { - String header = null; - StringBuilder stringBuilder = new StringBuilder("PayPalSDK/" - + PayPalResource.SDK_ID + " " + PayPalResource.SDK_VERSION - + " "); - stringBuilder.append("(").append(JAVAHEADER); - String osVersion = OSHEADER; - if (osVersion.length() > 0) { - stringBuilder.append(";").append(osVersion); - } - stringBuilder.append(")"); - header = stringBuilder.toString(); - return header; - } - -} diff --git a/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTUtil.java b/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTUtil.java deleted file mode 100644 index 657ff504..00000000 --- a/rest-api-sdk/src/main/java/com/paypal/core/rest/RESTUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.paypal.core.rest; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class RESTUtil { - - /** - * Formats the URI path for REST calls. - * - * @param pattern - * URI pattern with place holders for replacement strings - * @param parameters - * Replacement objects - * @return Formatted URI path - */ - public static String formatURIPath(String pattern, Object[] parameters) { - String formattedPath = null; - - if (pattern != null) { - if (parameters != null && parameters.length == 1 - && parameters[0] instanceof QueryParameters) { - - // Form a object array using the passed QueryParameters - parameters = splitParameters(pattern, - ((QueryParameters) parameters[0]).getContainerMap()); - } else if (parameters != null && parameters.length == 1 - && parameters[0] instanceof Map) { - - // Form a object array using the passed Map - parameters = splitParameters(pattern, - ((Map) parameters[0])); - } - - // Perform a simple message formatting - String fString = MessageFormat.format(pattern, parameters); - - // Process the resultant string for removing nulls - formattedPath = removeNullsInQS(fString); - } - return formattedPath; - } - - /** - * Remove null parameters from query string - * - * @param fString - * Formatted String - * @return Nulls removed query string - */ - private static String removeNullsInQS(String fString) { - if (fString != null && fString.length() != 0) { - String[] parts = fString.split("\\?"); - - // Process the query string part - if (parts.length == 2) { - String queryString = parts[1]; - String[] querys = queryString.split("&"); - if (querys.length > 0) { - StringBuilder strBuilder = new StringBuilder(); - for (String query : querys) { - String[] valueSplit = query.split("="); - if (valueSplit.length == 2) { - if ("null".equalsIgnoreCase(valueSplit[1].trim())) { - continue; - } else if ("".equals(valueSplit[1].trim())) { - continue; - } else { - strBuilder.append(query).append("&"); - } - } else if (valueSplit.length < 2) { - continue; - } - } - fString = (!strBuilder.toString().endsWith("&")) ? strBuilder - .toString() : strBuilder.toString().substring(0, - strBuilder.toString().length() - 1); - } - - // append the query string delimiter - fString = (parts[0].trim() + "?") + fString; - } - } - return fString; - } - - /** - * Split the URI and form a Object array using the query string and values - * in the provided map. The return object array is populated only if the map - * contains valid value for the query name. The object array contains null - * values if there is no value found in the map - * - * @param pattern - * URI pattern - * @param containerMap - * Map containing the query name and value - * @return Object array - */ - private static Object[] splitParameters(String pattern, - Map containerMap) { - List objectList = new ArrayList(); - String[] query = pattern.split("\\?"); - if (query != null && query.length == 2 && query[1].contains("={")) { - String[] queries = query[1].split("&"); - if (queries != null) { - for (String q : queries) { - String[] params = q.split("="); - if (params != null && params.length == 2) { - String key = params[0].trim(); - if (containerMap.containsKey(key)) { - Object object = containerMap.get(key); - objectList.add(object); - } else { - objectList.add(null); - } - } - } - } - } - return objectList.toArray(); - } - -} diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/AddressTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/AddressTestCase.java index a8ebbe28..10d95632 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/AddressTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/AddressTestCase.java @@ -5,8 +5,6 @@ public class AddressTestCase { -// public static final String RECIPIENTSNAME = "TestUser"; - public static final String CITY = "Niagara Falls"; public static final String COUNTRYCODE = "US"; @@ -21,11 +19,8 @@ public class AddressTestCase { public static final String STATE = "NY"; - public static final String TYPE = "Business"; - public static Address createAddress() { Address billingAddress = new Address(); -// billingAddress.setRecipientName(RECIPIENTSNAME); billingAddress.setCity(CITY); billingAddress.setCountryCode(COUNTRYCODE); billingAddress.setLine1(LINE1); @@ -33,14 +28,12 @@ public static Address createAddress() { billingAddress.setPostalCode(POSTALCODE); billingAddress.setPhone(PHONE); billingAddress.setState(STATE); - billingAddress.setType(TYPE); return billingAddress; } @Test public void testConstruction() { Address address = createAddress(); -// Assert.assertEquals(address.getRecipientName(), RECIPIENTSNAME); Assert.assertEquals(address.getCity(), CITY); Assert.assertEquals(address.getCountryCode(), COUNTRYCODE); Assert.assertEquals(address.getLine1(), LINE1); @@ -48,7 +41,6 @@ public void testConstruction() { Assert.assertEquals(address.getPostalCode(), POSTALCODE); Assert.assertEquals(address.getPhone(), PHONE); Assert.assertEquals(address.getState(), STATE); - Assert.assertEquals(address.getType(), TYPE); } @Test diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountTestCase.java index e1f80749..78daa2e5 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountTestCase.java @@ -7,8 +7,8 @@ public class AmountTestCase { public static final String CURRENCY = "USD"; - public static final AmountDetails AMOUNTDETAILS = AmountDetailsTestCase - .createAmountDetails(); + public static final Details AMOUNTDETAILS = DetailsTestCase + .createDetails(); public static Amount createAmount(String total) { Amount amount = new Amount(); @@ -24,7 +24,7 @@ public void testConstruction() { Assert.assertEquals(amount.getTotal(), "1000.00"); Assert.assertEquals(amount.getCurrency(), CURRENCY); Assert.assertEquals(amount.getDetails().getFee(), - AmountDetailsTestCase.FEE); + DetailsTestCase.FEE); } @Test diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/AuthorizationTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/AuthorizationTestCase.java index b184c7c2..bb9345e9 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/AuthorizationTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/AuthorizationTestCase.java @@ -1,13 +1,24 @@ package com.paypal.api.payments; +import java.io.File; import java.util.ArrayList; import java.util.List; import org.testng.Assert; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.testng.log4testng.Logger; + +import com.paypal.core.ConfigManager; +import com.paypal.core.rest.OAuthTokenCredential; +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; public class AuthorizationTestCase { + private static final Logger logger = Logger + .getLogger(AuthorizationTestCase.class); + public static final String ID = "12345"; public static final String PARENTPAYMENT = "12345"; @@ -18,9 +29,20 @@ public class AuthorizationTestCase { public static final String CREATEDTIME = "2013-01-17T18:12:02.347Z"; + public String authorizationId = null; + + public Authorization authorization = null; + + @BeforeClass + public void beforeClass() throws PayPalRESTException { + File testFile = new File(".", + "src/test/resources/sdk_config.properties"); + PayPalResource.initConfig(testFile); + } + public static Authorization createAuthorization() { - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); Authorization authorization = new Authorization(); authorization.setId(ID); authorization.setParentPayment(PARENTPAYMENT); @@ -43,6 +65,72 @@ public void testConstruction() { AmountTestCase.CURRENCY); } + @Test(dependsOnMethods = { "testGetRefundForNull" }) + public void testGetAuthorization() throws PayPalRESTException { + logger.info("**** Authorize Payment ****"); + Payment payment = getPaymentAgainstAuthorization(); + Payment authPayment = payment.create(TokenHolder.accessToken); + logger.info("Authorization Payment created with ID = " + + authPayment.getId()); + authorizationId = authPayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId(); + logger.info("Retrieving Authorization using id = " + authorizationId); + authorization = Authorization.get(TokenHolder.accessToken, + authorizationId); + Assert.assertEquals(authorization.getId(), authPayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId()); + logger.info("Request = " + Authorization.getLastRequest()); + logger.info("Response = " + Authorization.getLastResponse()); + logger.info("Authorization State: " + authorization.getState()); + } + + @Test(dependsOnMethods = { "testGetAuthorization" }) + public void testAuthorizationCapture() throws PayPalRESTException { + logger.info("**** Capture Authorization ****"); + Capture capture = new Capture(); + Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + capture.setAmount(amount); + capture.setIsFinalCapture(true); + Capture responsecapture = authorization.capture( + TokenHolder.accessToken, capture); + Assert.assertEquals(responsecapture.getState(), "completed"); + logger.info("Request = " + Authorization.getLastRequest()); + logger.info("Response = " + Authorization.getLastResponse()); + logger.info("Returned Capture state: " + responsecapture.getState()); + } + + @Test(dependsOnMethods = { "testAuthorizationCapture" }) + public void testAuthorizationVoid() throws PayPalRESTException { + logger.info("**** Void Authorization ****"); + Authorization auth = getAuthorization(); + Authorization responseAuthorization = auth + .doVoid(TokenHolder.accessToken); + Assert.assertEquals(responseAuthorization.getState(), "voided"); + logger.info("Request = " + Authorization.getLastRequest()); + logger.info("Response = " + Authorization.getLastResponse()); + logger.info("Returned Authorization state: " + + responseAuthorization.getState()); + } + + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testAuthorizationNullAccessToken() throws PayPalRESTException { + logger.info("**** Get Authorization (Null Access Token) ****"); + Authorization auth = Authorization.get((String) null, "123"); + } + + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testAuthorizationNullAuthId() throws PayPalRESTException { + logger.info("**** Get Authorization (Null Auth ID) ****"); + Authorization auth = Authorization.get(TokenHolder.accessToken, null); + } + + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testAuthorizationNullCapture() throws PayPalRESTException { + logger.info("**** Capture Authorization (Null Capture) ****"); + Capture responsecapture = getAuthorization().capture(TokenHolder.accessToken, null); + } + @Test public void testTOJSON() { Authorization authorization = createAuthorization(); @@ -55,4 +143,52 @@ public void testTOString() { Assert.assertEquals(authorization.toString().length() == 0, false); } + private Payment getPaymentAgainstAuthorization() { + Address billingAddress = AddressTestCase.createAddress(); + + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("7"); + + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + List transactions = new ArrayList(); + transactions.add(transaction); + + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + List fundingInstrumentList = new ArrayList(); + fundingInstrumentList.add(fundingInstrument); + + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstrumentList); + payer.setPaymentMethod("credit_card"); + + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + return payment; + } + + private Authorization getAuthorization() throws PayPalRESTException { + Payment payment = getPaymentAgainstAuthorization(); + Payment authPayment = payment.create(TokenHolder.accessToken); + Authorization authorization = authPayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization(); + return authorization; + } + } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/CaptureTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/CaptureTestCase.java index 75f1ae4d..a0b94d02 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/CaptureTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/CaptureTestCase.java @@ -1,16 +1,23 @@ package com.paypal.api.payments; +import java.io.File; import java.util.ArrayList; import java.util.List; import org.testng.Assert; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.testng.log4testng.Logger; + +import com.paypal.core.rest.PayPalRESTException; +import com.paypal.core.rest.PayPalResource; public class CaptureTestCase { - public static final String AUTHID = "12345"; + private static final Logger logger = Logger + .getLogger(CaptureTestCase.class); - public static final String DESCRIPTION = "sample description"; + public static final String AUTHID = "12345"; public static final String ID = "12345"; @@ -22,12 +29,19 @@ public class CaptureTestCase { public static final String CREATEDTIME = "2013-01-17T18:12:02.347Z"; + private Capture retrievedCapture = null; + + @BeforeClass + public void beforeClass() throws PayPalRESTException { + File testFile = new File(".", + "src/test/resources/sdk_config.properties"); + PayPalResource.initConfig(testFile); + } + public static Capture createCapture() { - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); Capture capture = new Capture(); - capture.setAuthorizationId(AUTHID); - capture.setDescription(DESCRIPTION); capture.setId(ID); capture.setParentPayment(PARENTPAYMENT); capture.setState(STATE); @@ -41,8 +55,6 @@ public static Capture createCapture() { public void testConstruction() { Capture capture = createCapture(); Assert.assertEquals(capture.getId(), ID); - Assert.assertEquals(capture.getAuthorizationId(), AUTHID); - Assert.assertEquals(capture.getDescription(), DESCRIPTION); Assert.assertEquals(capture.getParentPayment(), PARENTPAYMENT); Assert.assertEquals(capture.getState(), STATE); Assert.assertEquals(capture.getAmount().getCurrency(), @@ -51,6 +63,71 @@ public void testConstruction() { Assert.assertEquals(capture.getLinks().size(), 1); } + @Test(dependsOnMethods = { "testAuthorizationVoid" }) + public void testGetCapture() throws PayPalRESTException { + logger.info("**** Get Capture ****"); + Payment payment = getPaymentAgainstAuthorization(); + Payment authPayment = payment.create(TokenHolder.accessToken); + String authorizationId = authPayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId(); + Authorization authorization = Authorization.get( + TokenHolder.accessToken, authorizationId); + Capture capture = new Capture(); + Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + capture.setAmount(amount).setIsFinalCapture(true); + Capture responsecapture = authorization.capture( + TokenHolder.accessToken, capture); + logger.info("Generated Capture Id = " + responsecapture.getId()); + retrievedCapture = Capture.get(TokenHolder.accessToken, + responsecapture.getId()); + logger.info("Request = " + Capture.getLastRequest()); + logger.info("Response = " + Capture.getLastResponse()); + logger.info("Retrieved Capture State: " + retrievedCapture.getState()); + } + + @Test(dependsOnMethods = { "testGetCapture" }) + public void testRefundCapture() throws PayPalRESTException { + logger.info("**** Refund Capture ****"); + Refund refund = new Refund(); + Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + refund.setAmount(amount); + Refund responseRefund = retrievedCapture.refund( + TokenHolder.accessToken, refund); + Assert.assertEquals("completed", responseRefund.getState()); + logger.info("Request = " + Capture.getLastRequest()); + logger.info("Response = " + Capture.getLastResponse()); + logger.info("Refund State: " + responseRefund.getState()); + } + + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testGetCaptureNullCaptureId() throws PayPalRESTException { + logger.info("**** Get Capture (Null Capture Id) ****"); + Capture capture = Capture.get(TokenHolder.accessToken, null); + } + + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testCaptureNullRefund() throws PayPalRESTException { + logger.info("**** Get Capture (Null Refund) ****"); + Payment payment = getPaymentAgainstAuthorization(); + Payment authPayment = payment.create(TokenHolder.accessToken); + String authorizationId = authPayment.getTransactions().get(0) + .getRelatedResources().get(0).getAuthorization().getId(); + Authorization authorization = Authorization.get( + TokenHolder.accessToken, authorizationId); + Capture capture = new Capture(); + Amount amount = new Amount(); + amount.setCurrency("USD").setTotal("1"); + capture.setAmount(amount).setIsFinalCapture(true); + Capture responsecapture = authorization.capture( + TokenHolder.accessToken, capture); + logger.info("Generated Capture Id = " + responsecapture.getId()); + Capture rCapture = Capture.get(TokenHolder.accessToken, + responsecapture.getId()); + rCapture.refund(TokenHolder.accessToken, null); + } + @Test public void testTOJSON() { Capture capture = createCapture(); @@ -63,4 +140,44 @@ public void testTOString() { Assert.assertEquals(capture.toString().length() == 0, false); } + private Payment getPaymentAgainstAuthorization() { + Address billingAddress = AddressTestCase.createAddress(); + + CreditCard creditCard = new CreditCard(); + creditCard.setBillingAddress(billingAddress); + creditCard.setCvv2("874"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); + creditCard.setFirstName("Joe"); + creditCard.setLastName("Shopper"); + creditCard.setNumber("4417119669820331"); + creditCard.setType("visa"); + + Amount amount = new Amount(); + amount.setCurrency("USD"); + amount.setTotal("7"); + + Transaction transaction = new Transaction(); + transaction.setAmount(amount); + transaction + .setDescription("This is the payment transaction description."); + List transactions = new ArrayList(); + transactions.add(transaction); + + FundingInstrument fundingInstrument = new FundingInstrument(); + fundingInstrument.setCreditCard(creditCard); + List fundingInstrumentList = new ArrayList(); + fundingInstrumentList.add(fundingInstrument); + + Payer payer = new Payer(); + payer.setFundingInstruments(fundingInstrumentList); + payer.setPaymentMethod("credit_card"); + + Payment payment = new Payment(); + payment.setIntent("authorize"); + payment.setPayer(payer); + payment.setTransactions(transactions); + return payment; + } + } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTestCase.java index 8bdb5f4e..d37e26d8 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/CreditCardTestCase.java @@ -32,9 +32,9 @@ public class CreditCardTestCase { public static final String LASTNAME = "Shopper"; - public static final String EXPMONTH = "11"; + public static final int EXPMONTH = 11; - public static final String EXPYEAR = "2018"; + public static final int EXPYEAR = 2018; public static final String CVV2 = "874"; @@ -58,19 +58,11 @@ public void beforeClass() throws PayPalRESTException { public static CreditCard createCreditCard() { CreditCard creditCard = new CreditCard(); - creditCard.setBillingAddress(BILLINGADDRESS); - creditCard.setExpireMonth(EXPMONTH); - creditCard.setExpireYear(EXPYEAR); - creditCard.setFirstName(FIRSTNAME); - creditCard.setLastName(LASTNAME); - creditCard.setNumber(NUMBER); - creditCard.setType(TYPE); - creditCard.setCvv2(CVV2); - creditCard.setBillingAddress(BILLINGADDRESS); - creditCard.setId(ID); - creditCard.setPayerId(PAYERID); - creditCard.setState(STATE); - creditCard.setValidUntil(VALIDUNTIL); + creditCard.setBillingAddress(BILLINGADDRESS).setExpireMonth(EXPMONTH) + .setExpireYear(EXPYEAR).setFirstName(FIRSTNAME) + .setLastName(LASTNAME).setNumber(NUMBER).setType(TYPE) + .setCvv2(CVV2).setBillingAddress(BILLINGADDRESS).setId(ID) + .setPayerId(PAYERID).setState(STATE).setValidUntil(VALIDUNTIL); return creditCard; } @@ -89,8 +81,8 @@ public static CreditCard createDummyCreditCard() { creditCard.setPayerId(PAYERID); creditCard.setState(STATE); creditCard.setValidUntil(VALIDUNTIL); - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); creditCard.setLinks(links); return creditCard; } @@ -140,7 +132,8 @@ public void getCreditCard() throws PayPalRESTException { logger.info("**** Get CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); - CreditCard retrievedCreditCard = CreditCard.get(TokenHolder.accessToken, createdCreditCardId); + CreditCard retrievedCreditCard = CreditCard.get( + TokenHolder.accessToken, createdCreditCardId); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); Assert.assertEquals( @@ -151,6 +144,18 @@ public void getCreditCard() throws PayPalRESTException { + retrievedCreditCard.getState()); } + + @Test(dependsOnMethods = { "getCreditCard" }) + public void deleteCreditCard() throws PayPalRESTException { + logger.info("**** Delete CreditCard ****"); + logger.info("Generated Access Token = " + TokenHolder.accessToken); + + CreditCard retrievedCreditCard = CreditCard.get( + TokenHolder.accessToken, createdCreditCardId); + retrievedCreditCard.delete(TokenHolder.accessToken); + logger.info("Request = " + CreditCard.getLastRequest()); + logger.info("Response = " + CreditCard.getLastResponse()); + } @Test(dependsOnMethods = { "getCreditCard" }) public void getCreditCardForNull() { @@ -167,7 +172,7 @@ public void getCreditCardForNull() { Assert.fail(); } } - + @Test public void testCreditCardUnknownFileConfiguration() { try { @@ -191,7 +196,7 @@ public void testCreditCardInputStreamConfiguration() { Assert.fail("[sdk_config.properties] file is not available"); } } - + @Test public void testCreditCardPropertiesConfiguration() { try { diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountDetailsTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/DetailsTestCase.java similarity index 75% rename from rest-api-sdk/src/test/java/com/paypal/api/payments/AmountDetailsTestCase.java rename to rest-api-sdk/src/test/java/com/paypal/api/payments/DetailsTestCase.java index bf43989e..4028e2f1 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/AmountDetailsTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/DetailsTestCase.java @@ -3,7 +3,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -public class AmountDetailsTestCase { +public class DetailsTestCase { public static final String FEE = "100.00"; @@ -13,8 +13,8 @@ public class AmountDetailsTestCase { public static final String TAX = "20.00"; - public static AmountDetails createAmountDetails() { - AmountDetails amountDetails = new AmountDetails(); + public static Details createDetails() { + Details amountDetails = new Details(); amountDetails.setFee(FEE); amountDetails.setShipping(SHIPPING); amountDetails.setSubtotal(SUBTOTAL); @@ -24,7 +24,7 @@ public static AmountDetails createAmountDetails() { @Test public void testConstruction() { - AmountDetails amountDetails = createAmountDetails(); + Details amountDetails = createDetails(); Assert.assertEquals(amountDetails.getFee(), FEE); Assert.assertEquals(amountDetails.getShipping(), SHIPPING); Assert.assertEquals(amountDetails.getSubtotal(), SUBTOTAL); @@ -33,13 +33,13 @@ public void testConstruction() { @Test public void testTOJSON() { - AmountDetails amountDetails = createAmountDetails(); + Details amountDetails = createDetails(); Assert.assertEquals(amountDetails.toJSON().length() == 0, false); } @Test public void testTOString() { - AmountDetails amountDetails = createAmountDetails(); + Details amountDetails = createDetails(); Assert.assertEquals(amountDetails.toString().length() == 0, false); } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/LinkTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/LinksTestCase.java similarity index 76% rename from rest-api-sdk/src/test/java/com/paypal/api/payments/LinkTestCase.java rename to rest-api-sdk/src/test/java/com/paypal/api/payments/LinksTestCase.java index d6375fe2..1efd3105 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/LinkTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/LinksTestCase.java @@ -3,7 +3,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -public class LinkTestCase { +public class LinksTestCase { public static final String HREF = "http://sample.com"; @@ -11,8 +11,8 @@ public class LinkTestCase { public static final String REL = "authorize"; - public static Link createLink() { - Link link = new Link(); + public static Links createLinks() { + Links link = new Links(); link.setHref(HREF); link.setMethod(METHOD); link.setRel(REL); @@ -21,7 +21,7 @@ public static Link createLink() { @Test public void testConstruction() { - Link link = LinkTestCase.createLink(); + Links link = LinksTestCase.createLinks(); Assert.assertEquals(link.getHref(), HREF); Assert.assertEquals(link.getRel(), REL); Assert.assertEquals(link.getMethod(), METHOD); @@ -29,13 +29,13 @@ public void testConstruction() { @Test public void testTOJSON() { - Link link = LinkTestCase.createLink(); + Links link = LinksTestCase.createLinks(); Assert.assertEquals(link.toJSON().length() == 0, false); } @Test public void testTOString() { - Link link = LinkTestCase.createLink(); + Links link = LinksTestCase.createLinks(); Assert.assertEquals(link.toString().length() == 0, false); } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentExecutionTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentExecutionTestCase.java index 50fb1b51..e856c4e3 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentExecutionTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentExecutionTestCase.java @@ -9,8 +9,8 @@ public class PaymentExecutionTestCase { public static PaymentExecution createPaymentExecution(){ - List transactions = new ArrayList(); - transactions.add(AmountTestCase.createAmount("100.00")); + List transactions = new ArrayList(); + transactions.add(TransactionsTestCase.createTransactions()); PaymentExecution pae=new PaymentExecution(); pae.setPayerId(PayerInfoTestCase.PAYERID); pae.setTransactions(transactions); @@ -21,8 +21,8 @@ public static PaymentExecution createPaymentExecution(){ public void testConstruction(){ PaymentExecution pae = createPaymentExecution(); Assert.assertEquals(pae.getPayerId(), PayerInfoTestCase.PAYERID); - Assert.assertEquals(pae.getTransactions().get(0).getTotal(),"100.00"); - Assert.assertEquals(pae.getTransactions().get(0).getCurrency(),AmountTestCase.CURRENCY); + Assert.assertEquals(pae.getTransactions().get(0).getAmount().getTotal(),"100.00"); + Assert.assertEquals(pae.getTransactions().get(0).getAmount().getCurrency(),AmountTestCase.CURRENCY); } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentHistoryTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentHistoryTestCase.java index 551bfb55..a8d4e32b 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentHistoryTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentHistoryTestCase.java @@ -26,7 +26,7 @@ public static PaymentHistory createPaymentHistory() { public void testConstruction() { PaymentHistory paymentHistory = PaymentHistoryTestCase .createPaymentHistory(); - Assert.assertEquals(paymentHistory.getCount(), COUNT); + Assert.assertEquals(paymentHistory.getCount(), COUNT.intValue()); Assert.assertEquals(paymentHistory.getNextId(), NEXTID); Assert.assertEquals(paymentHistory.getPayments().size(), 1); } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentTestCase.java index c04f4842..9e8065bb 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/PaymentTestCase.java @@ -62,22 +62,16 @@ public static Payment createCallPayment() { CreditCard creditCard = new CreditCard(); creditCard.setBillingAddress(billingAddress); creditCard.setCvv2("874"); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setFirstName("Joe"); creditCard.setLastName("Shopper"); creditCard.setNumber("4417119669820331"); creditCard.setType("visa"); - // AmountDetails amountDetails = new AmountDetails(); - // amountDetails.setShipping("10"); - // amountDetails.setSubtotal("75"); - // amountDetails.setTax("15"); - Amount amount = new Amount(); amount.setCurrency("USD"); amount.setTotal("7"); - // amount.setDetails(amountDetails); Transaction transaction = new Transaction(); transaction.setAmount(amount); @@ -108,22 +102,22 @@ public static Payment createPayment() { CreditCard creditCard = new CreditCard(); creditCard.setBillingAddress(billingAddress); creditCard.setCvv2("874"); - creditCard.setExpireMonth("11"); - creditCard.setExpireYear("2018"); + creditCard.setExpireMonth(11); + creditCard.setExpireYear(2018); creditCard.setFirstName("Joe"); creditCard.setLastName("Shopper"); creditCard.setNumber("4111111111111111"); creditCard.setType("visa"); - AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("10"); - amountDetails.setSubtotal("75"); - amountDetails.setTax("15"); + Details details = new Details(); + details.setShipping("10"); + details.setSubtotal("75"); + details.setTax("15"); Amount amount = new Amount(); amount.setCurrency("USD"); amount.setTotal("100"); - amount.setDetails(amountDetails); + amount.setDetails(details); Payee payee = new Payee(); payee.setMerchantId("NMXBYHSEL4FEY"); @@ -145,8 +139,8 @@ public static Payment createPayment() { payer.setFundingInstruments(fundingInstrumentList); payer.setPaymentMethod("credit_card"); - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); RedirectUrls redirectUrls = RedirectUrlsTestCase.createRedirectUrls(); @@ -162,15 +156,15 @@ public static Payment createPayment() { } public static Payment createPaymentForExecution() { - AmountDetails amountDetails = new AmountDetails(); - amountDetails.setShipping("10"); - amountDetails.setSubtotal("75"); - amountDetails.setTax("15"); + Details details = new Details(); + details.setShipping("10"); + details.setSubtotal("75"); + details.setTax("15"); Amount amount = new Amount(); amount.setCurrency("USD"); amount.setTotal("100"); - amount.setDetails(amountDetails); + amount.setDetails(details); RedirectUrls redirectUrls = new RedirectUrls(); redirectUrls.setCancelUrl("http://www.hawaii.com"); @@ -281,8 +275,21 @@ public void testGetPaymentHistoryAPI() throws PayPalRESTException { logger.info("Response = " + Payment.getLastResponse()); logger.info("Retrieved Payments count = " + paymentHistory.getCount()); } - + @Test(dependsOnMethods = { "testGetPaymentHistoryAPI" }) + public void testGetPaymentHistoryQueryParamsAPI() throws PayPalRESTException { + logger.info("**** Get Payment History ****"); + logger.info("Setting Access Token = " + TokenHolder.accessToken); + QueryParameters params = new QueryParameters(); + params.setCount("10"); + PaymentHistory paymentHistory = Payment.get(TokenHolder.accessToken, + params); + logger.info("Request = " + Payment.getLastRequest()); + logger.info("Response = " + Payment.getLastResponse()); + logger.info("Retrieved Payments count = " + paymentHistory.getCount()); + } + + @Test(dependsOnMethods = { "testGetPaymentHistoryQueryParamsAPI" }) public void testFailCreatePaymentAPI() { logger.info("**** Failing Create Payment ****"); logger.info("Setting Access Token = " + TokenHolder.accessToken); diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/RefundTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/RefundTestCase.java index cc772eeb..17060f0b 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/RefundTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/RefundTestCase.java @@ -21,8 +21,6 @@ public class RefundTestCase { public static final String CAPTUREID = "12345"; - public static final String DESCRIPTION = "sample description"; - public static final String ID = "12345"; public static final String PARENTPAYMENT = "12345"; @@ -43,11 +41,10 @@ public void beforeClass() throws PayPalRESTException { } public static Refund createRefund() { - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); Refund refund = new Refund(); refund.setCaptureId(CAPTUREID); - refund.setDescription(DESCRIPTION); refund.setId(ID); refund.setParentPayment(PARENTPAYMENT); refund.setSaleId(SALEID); @@ -63,7 +60,6 @@ public void testConstruction() { Refund refund = createRefund(); Assert.assertEquals(refund.getId(), ID); Assert.assertEquals(refund.getCaptureId(), CAPTUREID); - Assert.assertEquals(refund.getDescription(), DESCRIPTION); Assert.assertEquals(refund.getParentPayment(), PARENTPAYMENT); Assert.assertEquals(refund.getSaleId(), SALEID); Assert.assertEquals(refund.getState(), STATE); diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/SubTransactionTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/RelatedResourcesTestCase.java similarity index 77% rename from rest-api-sdk/src/test/java/com/paypal/api/payments/SubTransactionTestCase.java rename to rest-api-sdk/src/test/java/com/paypal/api/payments/RelatedResourcesTestCase.java index ca4304ae..e7466f5e 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/SubTransactionTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/RelatedResourcesTestCase.java @@ -3,7 +3,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -public class SubTransactionTestCase { +public class RelatedResourcesTestCase { public static final Sale SALE = SaleTestCase.createSale(); @@ -14,8 +14,8 @@ public class SubTransactionTestCase { public static final Capture CAPTURE = CaptureTestCase.createCapture(); - public static SubTransaction createSubTransaction() { - SubTransaction subTransaction = new SubTransaction(); + public static RelatedResources createRelatedResources() { + RelatedResources subTransaction = new RelatedResources(); subTransaction.setAuthorization(AUTHORIZATION); subTransaction.setCapture(CAPTURE); subTransaction.setRefund(REFUND); @@ -25,7 +25,7 @@ public static SubTransaction createSubTransaction() { @Test public void testConstruction() { - SubTransaction subTransaction = createSubTransaction(); + RelatedResources subTransaction = createRelatedResources(); Assert.assertEquals(subTransaction.getAuthorization().getId(), AuthorizationTestCase.ID); Assert.assertEquals(subTransaction.getSale().getId(), SaleTestCase.ID); @@ -37,13 +37,13 @@ public void testConstruction() { @Test public void testTOJSON() { - SubTransaction subTransaction = createSubTransaction(); + RelatedResources subTransaction = createRelatedResources(); Assert.assertEquals(subTransaction.toJSON().length() == 0, false); } @Test public void testTOString() { - SubTransaction subTransaction = createSubTransaction(); + RelatedResources subTransaction = createRelatedResources(); Assert.assertEquals(subTransaction.toString().length() == 0, false); } diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/ResourceTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/ResourceTestCase.java deleted file mode 100644 index a1084822..00000000 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/ResourceTestCase.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.paypal.api.payments; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ResourceTestCase { - - public static Resource createResource() { - Resource resource = new Resource(); - return resource; - } - - @Test - public void testTOJSON() { - Resource resource = ResourceTestCase.createResource(); - Assert.assertEquals(resource.toJSON().length() == 0, false); - } - - @Test - public void testTOString() { - Resource resource = ResourceTestCase.createResource(); - Assert.assertEquals(resource.toString().length() == 0, false); - } - -} diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/SaleTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/SaleTestCase.java index 809dc57d..99b4104b 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/SaleTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/SaleTestCase.java @@ -39,8 +39,8 @@ public void beforeClass() throws PayPalRESTException { } public static Sale createSale() { - List links = new ArrayList(); - links.add(LinkTestCase.createLink()); + List links = new ArrayList(); + links.add(LinksTestCase.createLinks()); Sale sale = new Sale(); sale.setAmount(AMOUNT); sale.setId(ID); @@ -71,7 +71,7 @@ public void testSaleRefundAPI() throws PayPalRESTException { Payment createdPayment = payment.create(TokenHolder.accessToken); List transactions = createdPayment.getTransactions(); - List subTransactions = transactions.get(0) + List subTransactions = transactions.get(0) .getRelatedResources(); String id = subTransactions.get(0).getSale().getId(); this.SALE_ID = id; diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionTestCase.java index 8ef42ee2..a34ea747 100644 --- a/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionTestCase.java +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionTestCase.java @@ -16,8 +16,8 @@ public class TransactionTestCase { public static Transaction createTransaction() { ItemList itemList = ItemListTestCase.createItemList(); - List relResources = new ArrayList(); - relResources.add(SubTransactionTestCase.createSubTransaction()); + List relResources = new ArrayList(); + relResources.add(RelatedResourcesTestCase.createRelatedResources()); Transaction transaction = new Transaction(); transaction.setAmount(AMOUNT); transaction.setPayee(PAYEE); diff --git a/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionsTestCase.java b/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionsTestCase.java new file mode 100644 index 00000000..32113423 --- /dev/null +++ b/rest-api-sdk/src/test/java/com/paypal/api/payments/TransactionsTestCase.java @@ -0,0 +1,35 @@ +package com.paypal.api.payments; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class TransactionsTestCase { + + public static final Amount AMOUNT = AmountTestCase.createAmount("100.00"); + + public static Transactions createTransactions() { + Transactions transactions = new Transactions(); + transactions.setAmount(AMOUNT); + return transactions; + } + + @Test + public void testConstruction() { + Transactions transactions = TransactionsTestCase.createTransactions(); + Assert.assertEquals(transactions.getAmount().getTotal(), "100.00"); + + } + + @Test + public void testTOJSON() { + Transactions transactions = TransactionsTestCase.createTransactions(); + Assert.assertEquals(transactions.toJSON().length() == 0, false); + } + + @Test + public void testTOString() { + Transactions transactions = TransactionsTestCase.createTransactions(); + Assert.assertEquals(transactions.toString().length() == 0, false); + } + +} diff --git a/rest-api-sdk/src/test/java/com/paypal/core/rest/OAuthTokenCredentialTestCase.java b/rest-api-sdk/src/test/java/com/paypal/core/rest/OAuthTokenCredentialTestCase.java deleted file mode 100644 index 1038c26d..00000000 --- a/rest-api-sdk/src/test/java/com/paypal/core/rest/OAuthTokenCredentialTestCase.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.paypal.core.rest; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.testng.log4testng.Logger; - -import com.paypal.api.payments.Payment; -import com.paypal.api.payments.PaymentTestCase; - -import com.paypal.core.ConfigManager; - -public class OAuthTokenCredentialTestCase { - - private static final Logger logger = Logger - .getLogger(PaymentTestCase.class); - - String clientID; - String clientSecret; - - @BeforeClass - public void beforeClass() { - // ##Load Configuration - // Load SDK configuration for - // the resource. - InputStream is = OAuthTokenCredentialTestCase.class - .getResourceAsStream("/sdk_config.properties"); - - try { - PayPalResource.initConfig(is); - } catch (PayPalRESTException e) { - logger.error(e.getMessage()); - } - clientID = ConfigManager.getInstance().getValue("clientID"); - clientSecret = ConfigManager.getInstance().getValue("clientSecret"); - } - - @Test(dependsOnMethods = { "testGetRefund" }) - public void testGetAccessToken() throws PayPalRESTException { - - OAuthTokenCredential merchantTokenCredential = new OAuthTokenCredential( - clientID, clientSecret); - - String accessToken = merchantTokenCredential.getAccessToken(); - logger.info("Generated Access Token = " + accessToken); - Assert.assertEquals(true, accessToken.length() > 0); - } - - @Test(dependsOnMethods = { "testGetAccessToken" }) - public void testErrorAccessToken() { - File testFile = new File(".", - "src/test/resources/error_sdk_config.properties"); - try { - Payment.initConfig(testFile); - clientID = ConfigManager.getInstance().getValue("clientID"); - clientSecret = ConfigManager.getInstance().getValue("clientSecret"); - OAuthTokenCredential merchantTokenCredential = new OAuthTokenCredential( - clientID, clientSecret); - String accessToken = merchantTokenCredential.getAccessToken(); - } catch (PayPalRESTException e) { - Assert.assertEquals(true, e.getCause() instanceof IOException); - } - } -} diff --git a/rest-api-sdk/src/test/java/com/paypal/core/rest/PayPalResourceTestCase.java b/rest-api-sdk/src/test/java/com/paypal/core/rest/PayPalResourceTestCase.java deleted file mode 100644 index 9b2057a3..00000000 --- a/rest-api-sdk/src/test/java/com/paypal/core/rest/PayPalResourceTestCase.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.paypal.core.rest; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Properties; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.paypal.api.payments.Payment; -import com.paypal.core.rest.PayPalRESTException; - -public class PayPalResourceTestCase { - - @Test - public void testUnknownFileConfiguration() { - try { - Payment.initConfig(new File("unknown.properties")); - } catch (PayPalRESTException e) { - Assert.assertEquals(e.getCause().getClass().getSimpleName(), - "FileNotFoundException"); - } - } - - @Test - public void testInputStreamConfiguration() { - try { - File testFile = new File(".", - "src/test/resources/sdk_config.properties"); - FileInputStream fis = new FileInputStream(testFile); - Payment.initConfig(fis); - } catch (PayPalRESTException e) { - Assert.fail("[sdk_config.properties] stream loading failed"); - } catch (FileNotFoundException e) { - Assert.fail("[sdk_config.properties] file is not available"); - } - } - - @Test - public void testPropertiesConfiguration() { - try { - File testFile = new File(".", - "src/test/resources/sdk_config.properties"); - Properties props = new Properties(); - FileInputStream fis = new FileInputStream(testFile); - props.load(fis); - Payment.initConfig(props); - } catch (FileNotFoundException e) { - Assert.fail("[sdk_config.properties] file is not available"); - } catch (IOException e) { - Assert.fail("[sdk_config.properties] file is not loaded into properties"); - } - } - -} diff --git a/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTConfigurationTestCase.java b/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTConfigurationTestCase.java deleted file mode 100644 index dd640d86..00000000 --- a/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTConfigurationTestCase.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.paypal.core.rest; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.paypal.api.payments.Payment; -import com.paypal.api.payments.Sale; - -public class RESTConfigurationTestCase { - - @Test(dependsOnMethods = { "testErrorAccessToken" }) - public void testRESTConfiguration() { - File testFile = new File(".", - "src/test/resources/error_sdk_config.properties"); - try { - Payment.initConfig(testFile); - RESTConfiguration restConfiguration = new RESTConfiguration(); - restConfiguration.setHttpMethod(HttpMethod.POST); - restConfiguration.setResourcePath("/a/b/c"); - restConfiguration.getHttpConfigurations(); - URL url = restConfiguration.getBaseURL(); - Assert.assertEquals(true, url.toString().endsWith("/")); - } catch (PayPalRESTException e) { - Assert.fail(); - } catch (MalformedURLException e) { - Assert.fail(); - } catch (URISyntaxException e) { - Assert.fail(); - } - } - - @Test(dependsOnMethods = { "testRESTConfiguration" }) - public void testRESTHeaderConfiguration() { - File testFile = new File(".", - "src/test/resources/error_sdk_config.properties"); - try { - Payment.initConfig(testFile); - RESTConfiguration restConfiguration = new RESTConfiguration(); - restConfiguration.setHttpMethod(HttpMethod.POST); - restConfiguration.setResourcePath("/a/b/c"); - restConfiguration.getHttpConfigurations(); - Map headers = restConfiguration.getHeaders(); - Assert.assertEquals(headers.size() != 0, true); - String header = headers.get("User-Agent"); - String[] hdrs = header.split("\\("); - hdrs = hdrs[1].split(";"); - Assert.assertEquals(hdrs.length == 4, true); - } catch (PayPalRESTException e) { - Assert.fail(); - } catch (MalformedURLException e) { - Assert.fail(); - } catch (URISyntaxException e) { - Assert.fail(); - } - } - - @Test(dependsOnMethods = { "testRESTHeaderConfiguration" }) - public void testRESTConfigurationURL() { - File testFile = new File(".", - "src/test/resources/error_sdk_config.properties"); - try { - Sale.initConfig(testFile); - RESTConfiguration restConfiguration = new RESTConfiguration(); - restConfiguration.setHttpMethod(HttpMethod.POST); - restConfiguration.setResourcePath("/a/b/c"); - String urlString = "https://sample.com"; - restConfiguration.setUrl(urlString); - URL returnURL = restConfiguration.getBaseURL(); - Assert.assertEquals(true, returnURL.toString().endsWith("/")); - } catch (PayPalRESTException e) { - Assert.fail(); - } catch (MalformedURLException e) { - Assert.fail(); - } - } -} diff --git a/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTUtilTest.java b/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTUtilTest.java deleted file mode 100644 index 1b392e7d..00000000 --- a/rest-api-sdk/src/test/java/com/paypal/core/rest/RESTUtilTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.paypal.core.rest; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class RESTUtilTest { - - @Test - public void testFormatURIPathForNull() { - String nullString = RESTUtil.formatURIPath(null, null); - Assert.assertNull(nullString); - } - - @Test - public void testFormatURIPathNoPattern() { - String pattern = "/a/b/c"; - String uriPath = RESTUtil.formatURIPath(pattern, null); - Assert.assertEquals(uriPath, pattern); - } - - @Test - public void testFormatURIPathNoQS() { - String pattern = "/a/b/{0}"; - Object[] parameters = new Object[] {"replace"}; - String uriPath = RESTUtil.formatURIPath(pattern, parameters); - Assert.assertEquals(uriPath, "/a/b/replace"); - } - - @Test - public void testFormatURIPath() { - String pattern = "/a/b/{0}?name={1}"; - Object[] parameters = new Object[] {"replace", "nameValue"}; - String uriPath = RESTUtil.formatURIPath(pattern, parameters); - Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); - } - - @Test - public void testFormatURIPathWithNull() { - String pattern = "/a/b/{0}?name={1}&age={2}"; - Object[] parameters = new Object[] {"replace", "nameValue", null}; - String uriPath = RESTUtil.formatURIPath(pattern, parameters); - Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); - } - - @Test - public void testFormatURIPathWithEmpty() { - String pattern = "/a/b/{0}?name={1}&age="; - Object[] parameters = new Object[] {"replace", "nameValue", null}; - String uriPath = RESTUtil.formatURIPath(pattern, parameters); - Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); - } - - @Test - public void testFormatURIPathTwoQS() { - String pattern = "/a/b/{0}?name={1}&age={2}"; - Object[] parameters = new Object[] {"replace", "nameValue", "1"}; - String uriPath = RESTUtil.formatURIPath(pattern, parameters); - Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue&age=1"); - } - -}