# Build an end-to-end application
source: https://developer.mastercard.com/track-search/documentation/tutorials-and-guides/build-an-end-to-end-application-tutorial/index.md

## Overview {#overview}

This tutorial walks you through the steps to create a simple Java application that makes an API call to the Search API in the Sandbox environment.
>
> #### What you will learn {#what-you-will-learn}
>
* How to set up the environment to develop a simple Java application  
* How to generate an API client using the OpenAPI Generator  
* How to make an API call  

## Technologies used {#technologies-used}

* [JDK 8](https://www.java.com/en/) or later
* Any IDE of your choice.

## Before you start {#before-you-start}

Before starting this tutorial, ensure that you have already completed the following:

* Created your project and retrieved the required credentials.
* Obtained the [Track Search open API specification](https://developer.mastercard.com/track-search/documentation/api-reference/index.md).

<br />

APIs used in this tutorial:   

* Search [View Documentation](https://developer.mastercard.com/track-search/documentation/index.md)

## What you will achieve {#what-you-will-achieve}

At the end of this tutorial, you will successfully complete the payment cancellation process in CDP.

## Next steps {#next-steps}

Click **Next** to get started.

## Create a Maven Project {#create-a-maven-project}

* Create a Maven project using [Spring Initializr](https://start.spring.io/) which sets your directory structure automatically.
* Select the appropriate option for each of the following fields:
  * Project
  * Language
  * Spring Boot
* complete the required metadata for the information provided below.:
  * Group
  * ArtifactId
  * Name
  * Description
  * Package name
  * Packaging
  * Java version

## Add Resources {#add-resources}

To add resources:

* Add the Search Open API specification to your Maven project resources folder.
* Add the generated Sandbox key (.p12 file) to your Maven project resources folder. The .p12 file is generated while creating your project on Mastercard Developers.

Your Maven project directory structure should appear as shown in the below screen shot:

![Maven-resources](https://static.developer.mastercard.com/content/track-search/uploads/maven-resources-updated.png)

## Update pom.xml file {#update-pomxml-file}

To update pom.xml file:

* In your IDE, add the [OpenAPI Generator maven plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin) to your project pom.xml file using the below Plugin configurations:

```java
<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>5.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/track-search.yaml</inputSpec>
        <generatorName>java</generatorName>
        <library>okhttp-gson</library>
        <generateApiTests>false</generateApiTests>
        <generateModelTests>false</generateModelTests>
        <generateApiTests>false</generateApiTests>
        <configOptions>
          <sourceFolder>src/gen/java/main</sourceFolder>
          <groupId>com.mastercard.developer</groupId>
          <artifactId>track-search-client</artifactId>
          <invokerPackage>com.mastercard.developer.track-search-reference-application</invokerPackage>
          <apiPackage>com.mastercard.developer.track-search-reference-application.api</apiPackage>
          <modelPackage>com.mastercard.developer.track-search-reference-application.model</modelPackage>
          <dateLibrary>java8</dateLibrary>
          <java8>true</java8>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>
```

Note: The [OpenAPI Generator](https://openapi-generator.tech/) generates API client libraries using OpenAPI Specification. It provides multiple generators and library templates to support multiple languages and frameworks. We will be using the java generator for this project.

* Add the following dependencies to your pom.xml file:

```java
<properties>

         <!-- You may configure java 11 and above versions as well -->

        <java.version>1.8</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>

       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<properties>

<dependencies>

           <!-- Required for to take care of adding correct Authorization header before sending the request  -->

<dependency>
    <groupId>com.mastercard.developer</groupId>
    <artifactId>oauth1-signer</artifactId>
    <version>1.5.1</version>
</dependency>

<!-- Open Api generator -->

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-cli</artifactId>
    <version>5.2.1</version>
    <scope>provided</scope>
</dependency>

<!-- Libraries used to make REST service calls -->

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
  </dependency>
  <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>logging-interceptor</artifactId>
    <version>4.9.1</version>
  </dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
  </dependency>
  <dependency>
    <groupId>io.gsonfire</groupId>
    <artifactId>gson-fire</artifactId>
    <version>1.8.3</version>
  </dependency>

  <!-- Javax dependency is must for Java 11 and above versions -->

  <dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation.api</artifactId>
    <version>1.3.1</version>
  </dependency>

</dependencies
```

Note: Refer the [Generating and Configuring a Mastercard API Client](https://developer.mastercard.com/platform/documentation/security-and-authentication/generating-and-configuring-a-mastercard-api-client/) page for more information.

## Generate the API Client {#generate-the-api-client}

To generate the API client:

* Run the Maven command **mvn clean compile** in terminal.

* A new folder named **target** is created within your root directory, which contains classes generated for the schemas, and the API calls defined within the OpenAPI specification. The generated classes are available in the **target** folder as shown in the below screen shot:

![target-maven-updated](https://static.developer.mastercard.com/content/track-search/uploads/target-maven.png)

## Make an API Call {#make-an-api-call}

To make an API call:

* Go to the `src/main/java/` folder, and create a Java file named TrackSearchMain.java.

* Before making the API call, update the program with your OAuth credentials.

  ```java
  String consumerKey = "<Consumer_key from your Mastercard Developers' project>";
  String signingKeyFilePath = "<Path to p12 file>";
  String signingKeyAlias = "<key_alias>";
  String signingKeyPassword = "<key_password>";
  PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);
  ```

* Instantiate a client with your authentication credentials, and the configuration object as interceptors before sending it.

```java
ApiClient client = new ApiClient();
client.setBasePath(https://sandbox.api.mastercard.com/track/search);
client.setDebugging(true);
client.setHttpClient(client.getHttpClient()
                           .newBuilder()
                           .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                           .build());

PaymentCardApi addCardApi = new TrackSearchApi(client);
```

The sample code block of TrackSearchMain.java after completing the above steps is as follows:

```java
package com.mastercard.track.search;
import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor;
import com.mastercard.developer.track_search_reference_application.ApiClient;
import com.mastercard.developer.track_search_reference_application.api.TrackSearchApi;
import com.mastercard.developer.track_search_reference_application.model.*;
import com.mastercard.developer.utils.AuthenticationUtils;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;

public class TrackSearchMain {


    public static void main(String[] args) throws Exception {



        TrackSearchApi trackSearchApi = new TrackSearchApi(getApiClient());



        // Post: /bulk-searches

        NewBulkSearch newBulkSearch = createNewBulkSearchRequest();

        NewBulkSearchResult newBulkSearchResult = trackSearchApi.submitBulkSearch(newBulkSearch);



        // GET: /bulk-searches/{bulk_search_id}

        BulkSearchStatus bulkSearchStatus = trackSearchApi.getBulkSearchStatus(newBulkSearchResult.getBulkSearchId());



        // GET: /bulk-searches/{bulk_search_id}/results

        if ("COMPLETED".equalsIgnoreCase(bulkSearchStatus.getStatus())) {

            BulkSearchResult bulkSearchResult = trackSearchApi.getBulkSearchResults(newBulkSearchResult.getBulkSearchId(), 0, 25);

        }

    }



    private static ApiClient getApiClient() throws Exception {

        ApiClient client = new ApiClient();



        // TODO : Update your credentials.

        String consumerKey = "<Consumer key>";

        String signingKeyFilePath = "<Path to p12 file>";

        String signingKeyAlias = "<keyalias>";

        String signingKeyPassword = "<keystorepassword>";





        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias,

                signingKeyPassword);



        client.setHttpClient(client.getHttpClient()

                .newBuilder()

                .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey)).build())

                .setBasePath(https://sandbox.api.mastercard.com/track/search);



        client.setDebugging(true);

        return client;

    }





    // You may update the request payload as per your need.

    public static NewBulkSearch createNewBulkSearchRequest() {

        List<OrganisationIdentification> organisationIdentifications = new ArrayList<>();

        OrganisationIdentification organisationIdentification = new OrganisationIdentification();

        organisationIdentification.setIdentification("12345789");

        organisationIdentification.setType("TXID");

        organisationIdentifications.add(organisationIdentification);



        BusinessAddress businessAddress = new BusinessAddress();

        businessAddress.setAddressLine1("10 Main St, Apt 3");

        businessAddress.setCountry("USA");

        businessAddress.setCountrySubDivision("NY");

        businessAddress.setPostCode("10577");

        businessAddress.setTownName("Fairfax");



        SearchRequestEntity searchRequestEntity = new SearchRequestEntity();

        searchRequestEntity.setSearchRequestId("434534");

        searchRequestEntity.setBusinessName("Starbucks");

        searchRequestEntity.setPhoneNumber("9175763488");

        searchRequestEntity.setEmailAddress(info@starbucks.com);

        searchRequestEntity.setCurrency("USD");

        searchRequestEntity.setPaymentMethod("CARD");

        searchRequestEntity.setPaymentTerms("Net 30");

        searchRequestEntity.setAnnualInvoiceCount("100");

        searchRequestEntity.setAnnualTransactionAmount("100000");

        searchRequestEntity.setAnnualNumberOfTransactions("100");

        searchRequestEntity.setBusinessAddress(businessAddress);

        searchRequestEntity.setOrganisationIdentifications(organisationIdentifications);



        List<SearchRequestEntity> requestEntityList = new ArrayList<>();

        requestEntityList.add(searchRequestEntity);



        List<OrganisationIdentification> requesterOrganisationIdentifications = new ArrayList<>();

        OrganisationIdentification requesterOrganisationIdentification = new OrganisationIdentification();

        requesterOrganisationIdentification.setIdentification("52345785");

        requesterOrganisationIdentification.setType("TXID");

        requesterOrganisationIdentifications.add(requesterOrganisationIdentification);



        RequestingBusinessAddress requestingBusinessAddress = new RequestingBusinessAddress();

        requestingBusinessAddress.setAddressLine1("25 Main St, Apt 3");

        requestingBusinessAddress.setCountry("USA");

        requestingBusinessAddress.setCountrySubDivision("VA");

        requestingBusinessAddress.setPostCode("10577");

        requestingBusinessAddress.setTownName("Fairfax");



        RequesterInformation requesterInformation = new RequesterInformation();

        requesterInformation.setOrganisationIdentifications(requesterOrganisationIdentifications);

        requesterInformation.setBusinessAddress(requestingBusinessAddress);

        return getNewBulkSearch(requestEntityList, requesterInformation);

    }



    static NewBulkSearch getNewBulkSearch(List<SearchRequestEntity> requestEntityList, RequesterInformation requesterInformation) {

        requesterInformation.setBpsProfileId(bestbuy.pay@track);

        requesterInformation.setEmailAddress(info@bestbuy.com);

        requesterInformation.setPhoneNumber("9175763489");

        NewBulkSearch newBulkSearch = new NewBulkSearch();

        newBulkSearch.setLookupType("BUYERS");

        newBulkSearch.setMaximumMatches(1);

        newBulkSearch.setMinimumConfidenceThreshold("0.6");

        newBulkSearch.setSearches(requestEntityList);

        newBulkSearch.setRequestingEntity(requesterInformation);

        return newBulkSearch;

    }

}
```

