# Build an end-to-end application
source: https://developer.mastercard.com/doconomy-aland-index/documentation/tutorials-and-guides/ref-app-tutorial/index.md

This tutorial helps you to create a simple Java application that makes an API call to the Doconomy Aland Index API in the Sandbox environment.
You can refer to the reference application available [here](https://developer.mastercard.com/doconomy-aland-index/documentation/reference-app/index.md).
>
> #### 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 library with OpenAPI Generator.
* How to make an API call.

> #### Estimated time to complete this tutorial. {#estimated-time-to-complete-this-tutorial}
>
> * 15-20 minutes.

## Environment Set up {#environment-set-up}

### 1. Pre-requisites {#1-pre-requisites}

To complete this tutorial, you will need:

* JDK 17 or later.
* IntelliJ IDEA (or any other IDE of your choice).
* Mastercard Developers account with access to the Doconomy Aland Index API.
* Doconomy Aland Index Open API specification (Retrieved by clicking 'Open Specification' [here](https://developer.mastercard.com/doconomy-aland-index/documentation/api-reference/index.md)).

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

For this tutorial, IntelliJ IDEA as the IDE is used.

* In IntelliJ IDEA, create a new Maven project which sets your directory structure automatically.
* Provide ArtifactId and Project name as per your choice.

### 3. Add Resources {#3-add-resources}

* Add the Doconomy Aland Index Open API specification to your Maven project resources folder.
* Add the generated .p12 file to your Maven project resources folder. (Generated while creating your project on Mastercard Developers).
* Your Maven project directory structure should appear as:

![Directory Structure](https://static.developer.mastercard.com/content/doconomy-aland-index/Images/directory-structure.PNG)

### 4. Update pom.xml file {#4-update-pomxml-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. Use the Plugin config as shown below.
* [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.

* Plugin

```Plugin
<build>
    <plugins>
        <plugin>
            <groupId>org.openapitools</groupId>
            <artifactId>openapi-generator-maven-plugin</artifactId>
            <version>4.3.1</version>
            <executions>
                <execution>
                    <id>Doconomy Aland Index REST Client</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
                        <generatorName>java</generatorName>
                        <configOptions>
                            <sourceFolder>src/gen/java/main</sourceFolder>
                            <hideGenerationTimestamp>true</hideGenerationTimestamp>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
```

* Add the following dependencies to your **pom.xml** file, these are required by OpenAPI Generator and Mastercard OAuth1 Signer libraries.

* Dependencies

```Dependencies
<properties>
    <java.version>17</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>
    <oauth1-signer-version>1.5.0</oauth1-signer-version>
    <gson-fire-version>1.8.4</gson-fire-version>
    <swagger-core-version>1.5.24</swagger-core-version>
    <okhttp-version>3.14.7</okhttp-version>
    <gson-version>2.11.0</gson-version>
    <commons-lang3-version>3.10</commons-lang3-version>
    <threetenbp-version>1.4.3</threetenbp-version>
    <javax-annotation-version>1.3.2</javax-annotation-version>
    <junit-version>4.13</junit-version>         
</properties>
<dependencies>
    <dependency>
        <groupId>com.mastercard.developer</groupId>
        <artifactId>oauth1-signer</artifactId>
        <version>${oauth1-signer-version}</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>${swagger-core-version}</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>okhttp</artifactId>
        <version>${okhttp-version}</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>logging-interceptor</artifactId>
        <version>${okhttp-version}</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>${gson-version}</version>
    </dependency>
    <dependency>
        <groupId>io.gsonfire</groupId>
        <artifactId>gson-fire</artifactId>
        <version>${gson-fire-version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.oltu.oauth2</groupId>
        <artifactId>org.apache.oltu.oauth2.client</artifactId>
        <version>1.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.threeten</groupId>
        <artifactId>threetenbp</artifactId>
        <version>${threetenbp-version}</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit-version}</version>
    </dependency>
    <dependency>
        <groupId>com.mastercard.developer</groupId>
        <artifactId>oauth1-signer</artifactId>
        <version>${oauth1-signer-version}</version>
    </dependency>
</dependencies>
```

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

## Generating the API Client {#generating-the-api-client}

* Now that you have all the dependencies you need, you can generate the source code. You can navigate to the project root directory within a terminal window and run **mvn clean compile**.


![Maven Command](https://static.developer.mastercard.com/content/doconomy-aland-index/Images/MavenCommand.PNG)

* Afterward, there should be a new folder named **target**, within your root directory, which contains classes generated for the schemas and API calls defined within the OpenAPI Specification. The generated classes can be found in the target folder as shown below.


![Generated Sources](https://static.developer.mastercard.com/content/doconomy-aland-index/Images/GeneratedModels.PNG)

## Making an API Call {#making-an-api-call}

* Under src/main/java/, create a Java file named **CarbonImpactApiMain.java**.
* To make the API call, you need to make your OAuth credentials available to the program to use.

* Java

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

* Now you need to instantiate a client with your authentication credentials before you can send it.

* Java

```java
ApiClient client = new ApiClient();
client.setBasePath("https://sandbox.api.mastercard.com");
client.setDebugging(true);
client.setReadTimeout(10000);
List<Interceptor> interceptors = client.getHttpClient().networkInterceptors();
interceptors.add(new ForceJsonResponseInterceptor());
interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));

CarbonImpactApi carbonImpactApi = new CarbonImpactApi(client);   
```

* The interceptor that you use to sign a request is also provided by the Mastercard OAuth library.

* Java

```java
private static class ForceJsonResponseInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            String withJsonFormatUrl = withJsonFormat(originalRequest.uri().toString());
            Request newRequest = originalRequest.newBuilder().url(withJsonFormatUrl).build();
            return chain.proceed(newRequest);
        }

        private String withJsonFormat(String uri) {
            StringBuilder newUri = new StringBuilder(uri);
            newUri.append(uri.contains("?") ? "&" : "?");
            newUri.append("Format=JSON");
            return newUri.toString();
        }
    }
```

* Content of CarbonImpactApiMain.java.

* Java

```java
package com.mastercard.developer.doconomyalandindex;

import com.mastercard.developer.interceptors.OkHttp2OAuth1Interceptor;
import com.mastercard.developer.utils.AuthenticationUtils;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.openapitools.client.ApiClient;
import org.openapitools.client.api.CarbonImpactApi;
import org.openapitools.client.model.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.util.List;

public class CarbonImpactApiMain {

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

        ApiClient client = new ApiClient();

        String consumerKey = "your consumer key";
        String signingKeyFilePath = "/path/to/your/key.p12";
        String signingKeyAlias = "your key alias";
        String signingKeyPassword = "your password";
        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);

        client.setBasePath("https://sandbox.api.mastercard.com/doconomy");
        client.setDebugging(true);
        client.setReadTimeout(40000);
        List<Interceptor> interceptors = client.getHttpClient().networkInterceptors();
        interceptors.add(new ForceJsonResponseInterceptor());
        interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));

        CarbonImpactApi carbonImpactApi = new CarbonImpactApi(client);

        System.out.println("Calling Calculate Transaction Footprint");

        MCTransactions mcTransactions = new MCTransactions()
                .addTransactionsItem(new MCTransaction().transactionId("TX-1")
                                             .mcc("3000").amount(
                                new MCAmount().currencyCode("EUR").value(new BigDecimal(150))));

        MCTransactionFootprints transactionFootprints = carbonImpactApi.footprintsByTransactionData(mcTransactions);

        System.out.println("Calculate Transaction Footprint response : " + transactionFootprints);


        System.out.println("Calling Get Supported Currencies");

        MCSupportedCurrencies currencies = carbonImpactApi.getSupportedCurrencies();

        System.out.println("Get Supported Currencies response : " + currencies);


        System.out.println("Calling Get Supported Merchant Categories");

        MCSupportedMerchantCategories mcSupportedMerchantCategories = carbonImpactApi.getSupportedMerchantCategories();

        System.out.println("Get Supported Merchant Categories response : " + mcSupportedMerchantCategories);


    }


    /**
     * Add "Format=JSON" to the request for the service/gateway to return a JSON response.
     */
    private static class ForceJsonResponseInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            String withJsonFormatUrl = withJsonFormat(originalRequest.uri().toString());
            Request newRequest = originalRequest.newBuilder().url(withJsonFormatUrl).build();
            return chain.proceed(newRequest);
        }

        private String withJsonFormat(String uri) {
            StringBuilder newUri = new StringBuilder(uri);
            newUri.append(uri.contains("?") ? "&" : "?");
            newUri.append("Format=JSON");
            return newUri.toString();
        }
    }
}
```

