Skip to main content

Hackrank test sample api consumption java code sample


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

Popular posts from this blog

Mastering Java Logging: A Guide to Debug, Info, Warn, and Error Levels

Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Logging is an essential aspect of application development and maintenance. It helps developers track application behavior and troubleshoot issues effectively. Java provides various logging levels to categorize messages based on their severity and purpose. This article covers all major logging levels: Trace , Debug , Info , Warn , Error , and Fatal , along with how these levels impact log printing. 1. Trace The Trace level is the most detailed logging level. It is typically used for granular debugging, such as tracking every method call or step in a complex computation. Use this level sparingly, as it can generate a large volume of log data. 2. Debug The Debug level provides detailed information useful during dev...

Choosing Between Envoy and NGINX Ingress Controllers for Kubernetes

As Kubernetes has become the standard for deploying containerized applications, ingress controllers play a critical role in managing how external traffic is routed to services within the cluster. Envoy and NGINX are two of the most popular options for ingress controllers, and each has its strengths, weaknesses, and ideal use cases. In this blog, we’ll explore: How both ingress controllers work. A detailed comparison of their features. When to use Envoy vs. NGINX for ingress management. What is an Ingress Controller? An ingress controller is a specialized load balancer that: Manages incoming HTTP/HTTPS traffic. Routes traffic to appropriate services based on rules defined in Kubernetes ingress resources. Provides features like TLS termination, path-based routing, and host-based routing. How Envoy Ingress Controller Works Envoy , initially built by Lyft, is a high-performance, modern service proxy and ingress solution. Here's how it operates in Kubernetes: Ingress Resource : You d...

Distributed Transactions in Microservices: Implementing the Saga Pattern

Managing distributed transactions is one of the most critical challenges in microservices architecture. Since microservices operate with decentralized data storage, traditional ACID transactions across services are not feasible. The Saga Pattern is a proven solution for ensuring data consistency in such distributed systems. In this blog, we’ll discuss: What is the Saga Pattern? Types of Saga Patterns : Orchestration vs. Choreography How to Choose Between Them Implementing Orchestration-Based Saga with Spring Boot An Approach to Event-Driven Saga with Kafka 1. What is the Saga Pattern? The Saga Pattern breaks a long-running distributed transaction into a series of smaller atomic transactions , each managed by a microservice. If any step fails, compensating actions are performed to roll back the preceding operations. Example: In an e-commerce system , a customer places an order: Payment is processed. Inventory is reserved. Shipping is scheduled. If inventory reservation fails, the paym...