# Java

<details>

<summary>Without Router - Current Approach</summary>

```java
// Assuming this as previous logic without Router
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

public class EntityRequest {
    private static final String BASE_URL = "http://fip-1.dev.sahamati.org.in/fip-simulate";
    private static final String RECIPIENT_ID = "FIP-SIMULATOR";

    public static void main(String[] args) {
        try {
            String response = executeDiscoveryRequest();
            performAnotherOperations(response);
            System.out.println("Account discovery successful.");
        } catch (Exception e) {
            System.out.println("Account discovery failed. Error: " + e.getMessage());
        } finally {
            System.out.println("Account discovery completed.");
        }
    }

    private static String executeDiscoveryRequest() throws Exception {
        String route = "/v2/Accounts/discover";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = getHttpConfig(BASE_URL, route, new HashMap<>(), new HashMap<>(), "POST");
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    private static HttpRequest getHttpConfig(String baseUrl, String route, Map<String, String> headers, Map<String, Object> data, String methodType) {
        String url = baseUrl + route;
        String jsonData = mapToJson(data);
        
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(jsonData))
                .header("Content-Type", "application/json");
        
        headers.forEach(builder::header);
        return builder.build();
    }

    private static void performAnotherOperations(String accountDiscoverResponse) {
        System.out.println("Perform another operations with the response: " + accountDiscoverResponse);
    }

    private static String mapToJson(Map<String, ?> data) {
        StringBuilder jsonData = new StringBuilder("{");
        for (Map.Entry<String, ?> entry : data.entrySet()) {
            jsonData.append("\"").append(entry.getKey()).append("\": \"").append(entry.getValue()).append("\",");
        }
        if (!data.isEmpty()) {
            jsonData.deleteCharAt(jsonData.length() - 1);  
        }
        jsonData.append("}");
        return jsonData.toString();
    }
}

```

</details>

<details>

<summary>With Router Integration</summary>

```java
// Changes to implementation to integrate with Router
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class EntityRequest {
    private static final String BASE_URL = "http://fip-1.dev.sahamati.org.in/fip-simulate";
    private static final String RECIPIENT_ID = "FIP-SIMULATOR";
    private static final String ROUTER_URL = "https://api.dev.sahamati.org.in/router";

    public static void main(String[] args) {
        try {
            String response = executeDiscoveryRequest();
            performAnotherOperations(response);
            System.out.println("Account discovery successful.");
        } catch (Exception e) {
            System.out.println("Account discovery failed. Error: " + e);
        } 
    }

    private static String executeDiscoveryRequest() throws Exception {
        String route = "/v2/Accounts/discover";
        String url = BASE_URL + route;
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = getHttpConfig(url, new HashMap<>(), new HashMap<>());
        // add Sahamati configuration [Start]
        request = addSahamatiConfiguration(request, route);
        // add Sahamati configuration [End]
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();  
    }

    private static HttpRequest getHttpConfig(String url, Map<String, String> headers, Map<String, Object> data) {
        String jsonData = JSONObject(data); 
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(jsonData))
                .header("Content-Type", "application/json");
        headers.forEach(builder::header);  
        return builder.build();
    }

    private static void performAnotherOperations(String accountDiscoverResponse) {
        System.out.println("Perform another operations with the response: " + accountDiscoverResponse);
    }

    private static String generateBase64EncodedJson(Map<String, String> json) {
        String jsonString = JSONObject(json);  
        return Base64.getEncoder().encodeToString(jsonString.getBytes());
    }

    private static String generateRequestMeta(String recipientId) {
        Map<String, String> context = new HashMap<>();
        context.put("recipient-id", recipientId);
        return generateBase64EncodedJson(context);
    }

    private static HttpRequest addSahamatiConfiguration(HttpRequest request, String route) {
        String newUrl = ROUTER_URL + route;
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(newUrl))
                .method(request.method(), request.bodyPublisher().orElse(HttpRequest.BodyPublishers.noBody()));
    
        request.headers().map().forEach((key, values) -> {
            for (String value : values) {
                builder.header(key, value);
            }
        });
        builder.header("x-request-meta", generateRequestMeta(RECIPIENT_ID));
        return builder.build();
    }
}

```

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.sahamati.org.in/sahamatinet-poc/integration-steps/integration-with-router/sample-code-snippets/java.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
