# Setting up the Project source: https://developer.mastercard.com/priceless-planet-carbon-tracker/tutorial/api-testing/step2/index.md ## Setting up the Project {#setting-up-the-project} 1. Now that you have all the dependencies configured, 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/priceless-planet-carbon-tracker/images/insomnia/2.PNG) 2. A folder named **target** is created 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. ![Generated Sources](https://static.developer.mastercard.com/content/priceless-planet-carbon-tracker/images/insomnia/3.PNG) 3. Under the `src/main/java/` folder path of your project, create the package name as **mastercard**. 4. Create a Java file named **CarbonCalculatorExperienceMain.java**. 5. Copy the content in the newly created CarbonCalculatorExperienceMain.java. ```java package mastercard; import com.mastercard.developer.encryption.FieldLevelEncryptionConfig; import com.mastercard.developer.encryption.FieldLevelEncryptionConfigBuilder; import com.mastercard.developer.interceptors.OkHttpFieldLevelEncryptionInterceptor; import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor; import com.mastercard.developer.utils.AuthenticationUtils; import com.mastercard.developer.utils.EncryptionUtils; import net.bytebuddy.utility.RandomString; import org.openapitools.client.ApiClient; import org.openapitools.client.api.IssuerApi; import org.openapitools.client.model.Address; import org.openapitools.client.model.AggregateCarbonScore; import org.openapitools.client.model.CardExpiry; import org.openapitools.client.model.Dashboard; import org.openapitools.client.model.Email; import org.openapitools.client.model.IssuerConfiguration; import org.openapitools.client.model.IssuerProfile; import org.openapitools.client.model.IssuerProfileDetails; import org.openapitools.client.model.UserName; import org.openapitools.client.model.UserProfile; import org.openapitools.client.model.UserReference; import org.openapitools.client.model.UpdateUserProfile; import java.security.PrivateKey; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CarbonCalculatorExperienceMain { private static final String binRange = ""; public static void main(String[] args) throws Exception { IssuerApi issuerApi = new IssuerApi(getApiClient(false)); IssuerApi issuerApiForEncryptionDecryption = new IssuerApi(getApiClient(true)); System.out.println("Calling Calculate Experience to Get Issuer Details"); IssuerProfileDetails issuerProfileDetails = issuerApi.getIssuer(); System.out.println("Calling Calculate Experience Get Issuer API response : " + issuerProfileDetails); System.out.println("------------------------------------------------------------------"); System.out.println("Calling Update Issuer Api"); IssuerConfiguration issuerConfiguration = new IssuerConfiguration(); issuerConfiguration.setSupportedAccountRange("5051"); Map preferredTheme=new HashMap<>(); preferredTheme.put("backgroundColor", "#FFFFFF"); preferredTheme.put("buttonTextColor","#FFFFFF"); preferredTheme.put("widgetBackgroundColor","#FFFFFF"); preferredTheme.put("fontColor","#000000"); preferredTheme.put("barGraphColor", "#111111"); preferredTheme.put("buttonColor","#999999"); issuerConfiguration.setPreferredTheme(preferredTheme); IssuerProfile issuerProfile = issuerApi.updateIssuer(issuerConfiguration); System.out.println("Update Issuer API Response : " + issuerProfile); System.out.println("------------------------------------------------------------------"); System.out.println("Calling User Registration Api"); UserReference userReference = issuerApiForEncryptionDecryption.userRegistration(getUserProfile()); System.out.println("User Registration Response : " + userReference); System.out.println("------------------------------------------------------------------"); System.out.println("Calling Get Aggregate Scores for given user API"); AggregateCarbonScore aggregateCarbonScore = issuerApi.getAggregateCarbonScore(userReference.getUserid()); System.out.println("Get Aggregate Scores for given user API Response : " + aggregateCarbonScore); System.out.println("------------------------------------------------------------------"); System.out.println("Calling Get DashBoard API"); Dashboard dashboard = issuerApiForEncryptionDecryption.getAuthToken(userReference.getUserid(), "en-US"); System.out.println("Get Dashboard API response: " + dashboard); System.out.println("------------------------------------------------------------------"); System.out.println("Calling Update User Api"); UserReference updateUserReference = issuerApiForEncryptionDecryption.updateUser(userReference.getUserid(), getUpdateUserProfile()); System.out.println("Update User Response : " + updateUserReference); System.out.println("------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------"); System.out.println("Calling Delete User API"); List userIds = new ArrayList<>(); userIds.add(userReference.getUserid()); List deletedUserIds = issuerApi.deleteUsers(userIds); System.out.println("Delete User Api response: " + deletedUserIds); } private static ApiClient getApiClient(boolean enableEncryption) throws Exception { ApiClient client = new ApiClient(); String consumerKey = ""; String signingKeyFilePath = "./src/main/resources/.p12"; String encryptionCertPath = "./src/main/resources/.pem"; String mcKeyFilePath = "./src/main/resources/.p12"; String signingKeyAlias = ""; String signingKeyPassword = ""; String mcKeyAlias = ""; String mcKeyPassword = ""; PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword); client.setBasePath("https://sandbox.api.mastercard.com/cts"); client.setDebugging(false); if (enableEncryption) { client.setHttpClient(client.getHttpClient() .newBuilder() .addInterceptor(new OkHttpFieldLevelEncryptionInterceptor( getEncryptionConfig(encryptionCertPath))) .addInterceptor(new OkHttpFieldLevelEncryptionInterceptor( decryptionConfig(mcKeyFilePath,mcKeyAlias,mcKeyPassword))) .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey)) .build()); } else { client.setHttpClient(client.getHttpClient() .newBuilder() .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey)) .build()); } return client; } private static FieldLevelEncryptionConfig getEncryptionConfig(String encryptionCertPath) { FieldLevelEncryptionConfig config = null; try { Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate(encryptionCertPath); config = FieldLevelEncryptionConfigBuilder .aFieldLevelEncryptionConfig() .withEncryptionCertificate(encryptionCertificate) .withEncryptionPath("$", "$") .withEncryptedValueFieldName("encryptedData") .withEncryptedKeyFieldName("encryptedKey") .withOaepPaddingDigestAlgorithmFieldName("oaepHashingAlgorithm") .withOaepPaddingDigestAlgorithm("SHA-256") .withEncryptionKeyFingerprintFieldName("publicKeyFingerprint") .withIvFieldName("iv") .withFieldValueEncoding(FieldLevelEncryptionConfig.FieldValueEncoding.HEX) .build(); } catch (Exception e) { // Log and resolve this error. } return config; } public static FieldLevelEncryptionConfig decryptionConfig(String keyFile, String keyAlias, String password) { FieldLevelEncryptionConfig config = null; try { PrivateKey key = EncryptionUtils.loadDecryptionKey(keyFile, keyAlias, password); config = FieldLevelEncryptionConfigBuilder .aFieldLevelEncryptionConfig() .withDecryptionKey(key) .withDecryptionPath("$", "$") .withEncryptedValueFieldName("encryptedData") .withEncryptedKeyFieldName("encryptedKey") .withOaepPaddingDigestAlgorithmFieldName("oaepHashingAlgorithm") .withOaepPaddingDigestAlgorithm("SHA-256") .withEncryptionKeyFingerprintFieldName("publicKeyFingerprint") .withIvFieldName("iv") .withFieldValueEncoding(FieldLevelEncryptionConfig.FieldValueEncoding.HEX) .build(); } catch (Exception e) { // Log and resolve this error. } return config; } public static UserProfile getUserProfile() { UserProfile userProfile = new UserProfile(); Email email = new Email(); email.setType("home"); email.setValue("PPCT" + new RandomString().nextString() + "@gmail.com"); userProfile.setEmail(email); UserName userName = new UserName(); userName.setFirstName("dummmyUserrz"); userName.setLastName("Useraf"); userProfile.setName(userName); userProfile.setCardholderName("dummyaqa User"); userProfile.setCardBaseCurrency("USD"); String cardNumber = new CreditCardGenerator().generate(binRange, 16); //A credit card number generator userProfile.setCardNumber(cardNumber); CardExpiry cardExpiry = new CardExpiry(); cardExpiry.setMonth("09"); cardExpiry.setYear("2039"); Address address = new Address(); address.setCountryCode("USA"); address.setLocality("rly station"); address.setPostalCode("11746"); address.setState("Huntington"); address.setLine1("7836 West Elm Street"); address.setLine2("Huntington 120"); address.setLine3("7832 West "); address.setType("work"); address.setCity("Brooklyn"); userProfile.setBillingAddress(address); userProfile.setExpiryInfo(cardExpiry); userProfile.setLocale("en-US"); return userProfile; } public static UpdateUserProfile getUpdateUserProfile() { UpdateUserProfile updateUserProfile = new UpdateUserProfile(); UserName userName = new UserName(); userName.setFirstName("dummmyUserrz"); userName.setLastName("Useraf"); updateUserProfile.setName(userName); Address address = new Address(); address.setCountryCode("USA"); address.setLocality("rly station"); address.setLine1("7836 West Elm Street"); address.setLine2("Huntington 1200"); address.setPostalCode("11746"); address.setState("Huntington"); address.setLine3("7832 West "); address.setType("work"); address.setCity("Brooklyn"); updateUserProfile.setBillingAddress(address); updateUserProfile.setLocale("en-US"); return updateUserProfile; } } ```
6. Configure your OAuth credentials in the sample code for the following parameters. Provide a path formatted as `./src/main/resources/keyalias-encryption.p12`. ```java String consumerKey = ""; String signingKeyFilePath = "./src/main/resources/.p12"; String encryptionCertPath = "./src/main/resources/.pem"; String mcKeyFilePath = "./src/main/resources/.p12" String signingKeyAlias = ""; String signingKeyPassword = ""; String mcKeyAlias = ""; String mcKeyPassword = ""; PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword); ```
7. Provide Bin Range in the following parameter. ```java private static final String binRange = ""; ```
8. To generate \*\*test cards\*\*, create a Java file named \*\*CreditCardGenerator.java\*\* and add the following code: ```java package mastercard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.SecureRandom; /** * A credit card number generator. * */ public class CreditCardGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(mastercard.CreditCardGenerator.class); private final SecureRandom random = new SecureRandom(); /** * @param bin The bank identification number, a set digits at the start of the credit card * number, used to identify the bank that is issuing the credit card. * @param length The total length (i.e. including the BIN) of the credit card number. * @return A randomly generated, valid, credit card number. */ public String generate(String bin, int length) { String creditCardNumber; // The number of random digits that we need to generate is equal to the // total length of the card number minus the start digits given by the // user, minus the check digit at the end. int randomNumberLength = length - (bin.length() + 1); StringBuilder builder = new StringBuilder(bin); for (int i = 0; i < randomNumberLength; i++) { int digit = this.random.nextInt(10); builder.append(digit); } // Do the Luhn algorithm to generate the check digit. int checkDigit = this.getCheckDigit(builder.toString()); builder.append(checkDigit); creditCardNumber = builder.toString(); LOGGER.info("Generated creditCardNumber {}", creditCardNumber); String lastFourDigits = creditCardNumber.substring(creditCardNumber.length() - 4); LOGGER.info("lastFourDigits of creditCardNumber {} ", lastFourDigits); return creditCardNumber; } /** * Generates the check digit required to make the given credit card number * valid (i.e. pass the Luhn check) * * @param number The credit card number for which to generate the check digit. * @return The check digit required to make the given credit card number * valid. */ private int getCheckDigit(String number) { // Get the sum of all the digits, however we need to replace the value // of the first digit, and every other digit, with the same digit // multiplied by 2. If this multiplication yields a number greater // than 9, then add the two digits together to get a single digit // number. // // The digits we need to replace will be those in an even position for // card numbers whose length is an even number, or those is an odd // position for card numbers whose length is an odd number. This is // because the Luhn algorithm reverses the card number, and doubles // every other number starting from the second number from the last // position. int sum = 0; for (int i = 0; i < number.length(); i++) { // Get the digit at the current position. int digit = Integer.parseInt(number.substring(i, (i + 1))); if ((i % 2) == 0) { digit = digit * 2; if (digit > 9) { digit = (digit / 10) + (digit % 10); } } sum += digit; } // The check digit is the number required to make the sum a multiple of // 10. int mod = sum % 10; return ((mod == 0) ? 0 : 10 - mod); } } ```
9. The project setup is completed. Compile and run the project. Observe the logs for API responses.