import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TransactionFetcher {
public static List<double[]> getTransaction(int locationId, String txnType) {
int page = 1;
List<double[]> transactions = new ArrayList<>();
while (true) {
try {
String urlString = "https://jsonmock.hackerrank.com/api/transactions/search?" +
"txnType=" + txnType + "&page=" + page;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
// Convert the response to JSON object
Map<String, Object> response = new Gson().fromJson(content.toString(), Map.class);
int totalPages = ((Double) response.get("total_pages")).intValue();
List<Map<String, Object>> data = (List<Map<String, Object>>) response.get("data");
for (Map<String, Object> value : data) {
Map<String, Object> location = (Map<String, Object>) value.get("location");
if (((Double) location.get("id")).intValue() == locationId) {
int userId = ((Double) value.get("userId")).intValue();
// Removing any non-numeric characters from the amount string
String amountString = (String) value.get("amount");
Pattern pattern = Pattern.compile("[^0-9.]");
Matcher matcher = pattern.matcher(amountString);
String amountCleaned = matcher.replaceAll("");
double amount = Double.parseDouble(amountCleaned);
amount = Math.round(amount * 100.0) / 100.0;
boolean found = false;
for (double[] transaction : transactions) {
if (transaction[0] == userId) {
transaction[1] += amount;
found = true;
break;
}
}
if (!found) {
transactions.add(new double[]{userId, amount});
}
}
}
if (page >= totalPages) {
break;
}
page++;
} catch (Exception e) {
e.printStackTrace();
}
}
if (transactions.isEmpty()) {
return Arrays.asList(new double[]{-1, -1});
}
transactions.sort(Comparator.comparingDouble(a -> a[0]));
return transactions;
}
public static void main(String[] args) {
List<double[]> result = getTransaction(1, "debit");
for (double[] transaction : result) {
System.out.println("UserId: " + (int) transaction[0] + ", Amount: " + transaction[1]);
}
}
}
Comments
Post a Comment