io.hcxprotocol.utils.Utils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hcx-integrator-sdk Show documentation
Show all versions of hcx-integrator-sdk Show documentation
The SDK for HCX Participant System to help in integrating with HCX Gateway easily.
package io.hcxprotocol.utils;
import io.hcxprotocol.dto.HttpResponse;
import io.hcxprotocol.exception.ClientException;
import io.hcxprotocol.exception.ServerException;
import lombok.experimental.UtilityClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The common utils functionality used in HCX Integrator SDK.
*
* - Generation of authentication token using HCX Gateway and Participant System Credentials.
* - HCX Gateway Participant Registry Search.
*
*/
@UtilityClass
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
// TODO: In the initial version we are not handling the token caching, it will be handled in the next version
public static String generateToken(String username, String password, String authBasePath) throws Exception {
Map headers = new HashMap<>();
headers.put("content-type", "application/x-www-form-urlencoded");
Map fields = new HashMap<>();
fields.put("client_id", "registry-frontend");
fields.put("username", username);
fields.put("password", password);
fields.put("grant_type", "password");
HttpResponse response = HttpUtils.post(authBasePath, headers, fields);
Map respMap = JSONUtils.deserialize(response.getBody(), Map.class);
String token;
if (response.getStatus() == 200) {
token = (String) respMap.get("access_token");
} else if (response.getStatus() == 401) {
logger.error("Error while generating API access token: Invalid credentials");
throw new ClientException("Error while generating API access token: Invalid credentials");
} else {
logger.error("Error while generating API access token :: status: " + response.status + " :: message: " + respMap);
throw new ServerException("Error while generating API access token :: status: " + response.status + " :: message: " + respMap);
}
return token;
}
public static Map searchRegistry(String participantCode, String token, String protocolBasePath) throws Exception {
String filter = "{\"filters\":{\"participant_code\":{\"eq\":\"" + participantCode + "\"}}}";
Map headers = new HashMap<>();
headers.put(Constants.AUTHORIZATION, "Bearer " + token);
HttpResponse response = HttpUtils.post(protocolBasePath + "/participant/search", headers, filter);
Map respMap = JSONUtils.deserialize(response.getBody(), Map.class);
List