# Java API Client
source: https://developer.mastercard.com/account-validation/documentation/tutorials-and-guides/api-tutorial/index.md

This tutorial generates a Java API client library using the OpenAPI Generator and Account Validation API specification and then builds a simple Java program that makes API calls to the Sandbox environment. You can also adapt this tutorial to [make API Calls to MTF](https://developer.mastercard.com/account-validation/documentation/tutorials-and-guides/api-tutorial/index.md#make-api-calls-to-mtf).

The Java program makes API calls with unencrypted payloads. To adapt it to use payload encryption/decryption, see [Add Payload Encryption](https://developer.mastercard.com/account-validation/documentation/tutorials-and-guides/api-tutorial-enc/index.md).

## Prerequisites {#prerequisites}

To complete this tutorial, you need:

* [Java 11+](https://www.java.com/en/download/manual.jsp). Ensure that your `JAVA_HOME` environment variable is pointing to your JDK installation or have the java executable on your `PATH` environment variable.
* [Maven 3.6.0+](https://maven.apache.org/download.cgi)
* Integrated Development Environment (IDE) of your choice. This tutorial uses the IntelliJ IDEA IDE.
* A Mastercard Developers [project](https://developer.mastercard.com/dashboard) created with the **Mastercard Account Validation** API service. This generated the Sandbox signing key (.p12 file) and credentials you will use to access the Sandbox environment. For guidance on creating a project, see the [quick start guide](https://developer.mastercard.com/platform/documentation/getting-started-with-mastercard-apis/quick-start-guide/).

## Generate a Client Application {#generate-a-client-application}

Note: This tutorial was developed using a Windows machine. You can follow the same steps in other Operating Systems (OS) as well.

In the File Explorer, create a folder in your desired location. In the same folder:

1. Download and save the
[account-validation-api-swagger.yaml](https://static.developer.mastercard.com/content/account-validation/swagger/account-validation-api-swagger.yaml) (29KB) file.

2. Download and save the latest [OpenAPI Generator CLI](https://openapi-generator.tech/docs/installation/#jar) jar directly from Maven.org.

3. Create a `config.json` file and add the following configurations to the file:

```json
{
   "groupId":"com.acme.app",
   "artifactId":"mastercard-api-client",
   "artifactVersion":"1.0.0",
   "invokerPackage":"com.acme.app.mastercard",
   "apiPackage":"com.acme.app.mastercard.api",
   "modelPackage":"com.acme.app.mastercard.model"
}  
```

Your current folder should look as follows:

![Folder with client generation files](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-1.png)

4. Open the Command Prompt and navigate to that folder.

5. Run the following command to generate the client application.

    openapi-generator-cli-7.8.0.jar generate -g java --library okhttp-gson -i account-validation-api-swagger.yaml -c config.json -o AccValClient

In the above command, alter these parts as necessary:

* Jar version number, for example, "7.8.0"
* Name of the swagger file, for example, "account-validation-api-swagger.yaml"
* Name of the desired client application, for example, "AccValClient"

After you run the command, the AccValClient application is generated within that folder as follows:

![Folder with generated client folder](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-2.png)

## Set up a Maven Project {#set-up-a-maven-project}

After generating the client application, complete the below Maven project setup to download the dependencies and generate the Java client library.

1. In the IntelliJ IDE, open the client application as a **Maven** project. Your IntelliJ IDE should look as follows:
![IntelliJ project window](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-3.png)

2. Edit the **pom.xml** file to add the below OAuth Client Authentication Library as one of the dependencies.

```xml
    <dependency>
        <groupId>com.mastercard.developer</groupId>
        <artifactId>oauth1-signer</artifactId>
        <version>1.5.2</version>
    </dependency>
```

For example:

![Where to add dependency in POM file](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-pom-example.png)

3. In the IntelliJ IDE, navigate to the Terminal window and run the below command:

    mvn clean install

After you have successfully run the command, a new folder named **target** is generated within your root directory, which contains classes generated for the schemas and API calls defined within the API specification. The generated classes can be found in the location `target/classes/com/acme/app/mastercard` as shown below.

![Project target folder contents](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-4.png)

4. Create a **resources** folder in the `./src/main/` location and copy the Sandbox signing key (.p12) file to that folder as shown below:

![Project key file](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-5.png)

## Make API Calls to Sandbox {#make-api-calls-to-sandbox}

The below steps and sample code demonstrate how to make an API call. You can either:

* Download and add the [AccountVal.java](https://static.developer.mastercard.com/content/account-validation/uploads/AccountVal.java) (4KB) file, then alter the code snippets as indicated below.
* Create a new Java class file, then add and alter the code snippets as indicated below.

Add or create the Java class file in the `./src/main/java` location as shown below:

![Java class file](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-6.png)

Open the `AccountVal.java` file and modify or add the following parts accordingly:

1. Add or adjust the code to import the required classes:

```java
import com.acme.app.mastercard.ApiClient;
import com.acme.app.mastercard.ApiException;
import com.acme.app.mastercard.api.AccountValidationApi;
import com.acme.app.mastercard.model.*;
import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor;
import com.mastercard.developer.utils.AuthenticationUtils;
import java.security.PrivateKey;
import java.util.Random;
```

If any external class libraries do not import automatically, you may need to click the **Reload All Maven Projects** button in the Maven project window (**View \> Tool Windows \> Maven**):

![Reload Maven projects](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-reload-projects.png)

2. Update the consumer key and signing key values to match your .p12 file and the Sandbox Credentials from your Mastercard Developers project. These will be used by the `AuthenticationUtils.loadSigningKey()` method to generate a private signing key object.

```java
        // Update these values to match your OAuth credentials
        String consumerKey = "your_consumer_key_WdnUc_-2345tF245A-_DE7f71c_-75!b10-_23451b440ab_-e210b12-_58f650000000000000000";
        String signingKeyAlias = "your_key_alias";
        String signingKeyFilePath = "./src/main/resources/GS_Account_Validation-sandbox-signing.p12";
        String signingKeyPassword = "your_key_password";

        // This method generates the signing key which can be used to sign your API requests
        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);

        // Set request header values
        String partnerId = "ptnr_1lzs0zD6uWo7k-OdUXjLW_pFgX2";
        Boolean xEncrypted = false;
        String contentType = "application/json";
        String accept = "application/json";
```

3. The base path is set to the Sandbox environment by default. You instantiate a client that can sign requests with your authentication credentials.

```java
        ApiClient apiClient = new ApiClient();

        apiClient.setBasePath("https://sandbox.api.move.mastercard.com/common");
        apiClient.setHttpClient(
                apiClient.getHttpClient()
                        .newBuilder()
                        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                        .build()
        );
```

4. You create a new `accountValidationApi` request object to make the API call to the `/account-validations` endpoint.

```java
        AccountValidationApi accountValidationApi = new AccountValidationApi(apiClient);
```

5. The `accountValidationCreateData` object sets the values to the Request Body fields that are required to make a successful API call to the endpoint. You can modify the values as required.   
Any nested objects within the Request Body have each been assigned a wrapper class, and so in order to build the request, you will be instantiating multiple objects and ultimately wrapping those with the main request object.

```java
        AccountValidationCreateData accountValidationCreateData = new AccountValidationCreateData();

        // This builder builds a unique reference ID to associate with the account validation request
        StringBuilder builder = new StringBuilder();
        builder.append("avs_");
        for (int i = 0; i < 10; i++) {
            builder.append(new Random().nextInt(10));
        }
        String referenceId = builder.toString();

        // Set the values for the accountDetails object
        AccountDetails accountDetails = new AccountDetails();
        Account account = new Account();
        account.setType("PAN");
        account.setNumber("5102589999999913");
        account.setExpiry("2050-10");
        account.setCvc("123");
        Name name = new Name();
        name.setFirstName("Jane");
        name.setMiddleName("Michelle");
        name.setLastName("Candy-Smith");
        accountDetails.setAccount(account);
        accountDetails.setName(name);

        // Set the values for the acquiringCredentials object
        AcquiringCredentials acquiringCredentials = new AcquiringCredentials();
        SingleMessage singleMessage = new SingleMessage();
        singleMessage.setProcessorId("9000001957");
        singleMessage.setAcquiringIdentificationCode("123456780");
        acquiringCredentials.setCountry("USA");
        acquiringCredentials.setSingleMessage(singleMessage);

        // Wrap each object into the main object and set other values
        accountValidationCreateData.setReferenceId(referenceId);
        accountValidationCreateData.setAccountDetails(accountDetails);
        accountValidationCreateData.setCurrency("USD");
        accountValidationCreateData.setTransactionLocalDateTime("2021-06-17T18:05:02");
        accountValidationCreateData.setAcquiringCredentials(acquiringCredentials);
```

6. You call the `createAccountValidationUsingPOST` function to make the API call to the `/account-validations` endpoint and store the response in an `accountValResponse` object. You can access the individual response values using the `accountValResponse.get()` method.

```java
        AccountValidation accountValResponse = null;

        try {
            accountValResponse = accountValidationApi.createAccountValidationUsingPOST(partnerId, accountValidationCreateData, xEncrypted, contentType, accept);
            System.out.println("Request:");
            System.out.println(accountValidationCreateData);
            System.out.println();
            System.out.println("Response:");
            System.out.println(accountValResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling AccountValidationApi#createAccountValidationUsingPOST");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

7. Build and run the Java class file. You can do this using the **Build Project** and **Run** buttons:

![Java class file](https://static.developer.mastercard.com/content/account-validation/documentation/images/api-tutorial-build-and-run.png)

#### Result {#result}

The successful API request produces the following response in the IntelliJ IDE Run window. The `status` values indicate the matching results.

    class AccountValidation {
        referenceId: avs_6655755238
        id: 81b3e82c-878a-472b-9b29-28d2320754c4
        networkResponseCode: 00
        networkResponseCodeDescription: Approved or completed successfully
        cvcValidationResults: class CvcValidationResults {
            status: NOT_MATCHED
            responseCode: N
            responseCodeDescription: CVV2 does not match
        }
        nameValidationResults: class NameValidationResults {
            status: NOT_MATCHED
            firstNameStatus: null
            middleNameStatus: null
            lastNameStatus: null
        }
    }

## Make API Calls to MTF {#make-api-calls-to-mtf}

You can make calls to the MTF environment when you have registered for this service and Mastercard has configured that environment for your Sandbox keys. You can adapt this tutorial code easily to call MTF:

* Adjust the base path to "https://mtf.api.move.mastercard.com/common".
* Change the `partnerId` header value to match your onboarded configuration.

You may need to adjust the code to pass request fields and values appropriate to the environment and your configuration, such as valid test account numbers and any required acquiring credentials.
