Skip to content

Commit

Permalink
Merge pull request #1672 from mohanachandran-s/develop
Browse files Browse the repository at this point in the history
MOSIP-37213 - Created websocket util for esignet-signup l2 flow api's
  • Loading branch information
mohanachandran-s authored Nov 18, 2024
2 parents 179be27 + b451995 commit 126df14
Show file tree
Hide file tree
Showing 4 changed files with 208 additions and 3 deletions.
5 changes: 5 additions & 0 deletions apitest-commons/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,11 @@
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>io.mosip.authentication</groupId>
<artifactId>authentication-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,13 +665,16 @@ public void getvalueFromResponseHeader(Response response, String testCaseName) {
if (eachSetCookieValue.trim().startsWith("IDV_TRANSACTION_ID")) {
getCookieAndWriteAutoGenId(eachSetCookieValue, "idvTransactionID", testCaseName);
}
if (eachSetCookieValue.trim().startsWith("IDV_SLOT_ALLOTTED")) {
getCookieAndWriteAutoGenId(eachSetCookieValue, "idvSlotAllotted", testCaseName);
}
}
}
}
}

protected void getCookieAndWriteAutoGenId(String cookieValue, String key, String testCaseName) {
if (!cookieValue.split("=")[1].isBlank()) {
if (cookieValue.split("=").length > 1 && !cookieValue.split("=")[1].isBlank()) {
String value = cookieValue.split("=")[1];
writeAutoGeneratedId(testCaseName, key, value);
}
Expand Down Expand Up @@ -720,8 +723,11 @@ protected Response postRequestWithCookieAuthHeaderAndXsrfTokenForAutoGenId(Strin
JSONObject request = new JSONObject(inputJson);
String encodedResp = null;
String transactionId = null;
String headerTransactionID = "";
String pathFragmentCookie = null;
String pathFragmentCookieTransactionId = null;
Map<String, String> cookiesMap = new HashMap<>();

if (request.has(GlobalConstants.ENCODEDHASH)) {
encodedResp = request.get(GlobalConstants.ENCODEDHASH).toString();
request.remove(GlobalConstants.ENCODEDHASH);
Expand All @@ -742,7 +748,7 @@ protected Response postRequestWithCookieAuthHeaderAndXsrfTokenForAutoGenId(Strin
request.remove(GlobalConstants.PATH_FRAGMENT_COOKIE_TRANSACTIONID);
request.remove(GlobalConstants.PATH_FRAGMENT_COOKIE);
}

inputJson = request.toString();
if (BaseTestCase.currentModule.equals(GlobalConstants.MIMOTO) || BaseTestCase.currentModule.equals("auth")
|| BaseTestCase.currentModule.equals(GlobalConstants.ESIGNET)
Expand All @@ -751,12 +757,24 @@ protected Response postRequestWithCookieAuthHeaderAndXsrfTokenForAutoGenId(Strin
}

token = properties.getProperty(GlobalConstants.XSRFTOKEN);

if (request.has(GlobalConstants.IDV_TRANSACTION_ID)) {
headerTransactionID = request.get(GlobalConstants.IDV_TRANSACTION_ID).toString();
headers.put(GlobalConstants.IDV_TRANSACTION_ID_KEY, headerTransactionID);
cookiesMap.put(GlobalConstants.IDV_TRANSACTION_ID_KEY, headerTransactionID);
cookiesMap.put(GlobalConstants.XSRF_TOKEN, token);
request.remove(GlobalConstants.IDV_TRANSACTION_ID);
}

logger.info(GlobalConstants.POST_REQ_URL + url);
GlobalMethods.reportRequest(headers.toString(), inputJson, url);
try {
if (pathFragmentCookie!=null) {
response = RestClient.postRequestWithMultipleHeadersAndMultipleCookies(url, inputJson, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, pathFragmentCookieTransactionId, pathFragmentCookie, headers);
} else if (cookiesMap.containsKey(GlobalConstants.IDV_TRANSACTION_ID_KEY)) {
response = RestClient.postRequestWithMultipleHeadersAndCookies(url, inputJson,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, cookiesMap, headers);
} else {
response = RestClient.postRequestWithMultipleHeadersAndCookies(url, inputJson, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, cookieName, token, headers);
Expand Down Expand Up @@ -794,8 +812,14 @@ protected Response getRequestWithCookieAuthHeaderAndXsrfToken(String url, String
headers.put(XSRF_HEADERNAME, properties.getProperty(GlobalConstants.XSRFTOKEN));
headers.put(OAUTH_HASH_HEADERNAME, encodedResp);
headers.put(OAUTH_TRANSID_HEADERNAME, transactionId);

token = null;

if (request.has(GlobalConstants.IDV_SLOT_ALLOTED)) {
token = request.get(GlobalConstants.IDV_SLOT_ALLOTED).toString();
cookieName = "IDV_SLOT_ALLOTTED";
request.remove(GlobalConstants.IDV_SLOT_ALLOTED);
}
logger.info(GlobalConstants.GET_REQ_STRING + url);
GlobalMethods.reportRequest(headers.toString(), null, url);
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,6 @@ public class GlobalConstants {
public static final String PATH_FRAGMENT_COOKIE_TRANSACTIONID = "pathFragmentCookieTransactionId";
public static final String IDV_TRANSACTION_ID = "idvTransactionID";
public static final String IDV_TRANSACTION_ID_KEY = "IDV_TRANSACTION_ID";
public static final String IDV_SLOT_ALLOTED = "idvSlotAllotted";
public static final String IDV_SLOT_ALLOTED_KEY = "IDV_SLOT_ALLOTTED=";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package io.mosip.testrig.apirig.utils;

import javax.websocket.*;
import org.apache.log4j.Logger;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ConcurrentHashMap;

@ClientEndpoint
public class WebSocketClientUtil extends Endpoint {

private static final Logger logger = Logger.getLogger(WebSocketClientUtil.class);
private Session session;
private CountDownLatch latch;
private String cookie;
private String subscribeDestination;
private String sendDestination;


// Global map to store received messages, keyed by message ID or custom key
private static final Map<String, String> messageStore = new ConcurrentHashMap<>();

public WebSocketClientUtil(String cookie, String subscribeDestination, String sendDestination) {
this.cookie = cookie;
this.subscribeDestination = subscribeDestination;
this.sendDestination = sendDestination;
latch = new CountDownLatch(1); // Initially, latch is set to 1
}

@Override
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
logger.info("WebSocket opened");

// Add message handler
session.addMessageHandler(String.class, this::onMessage);

try {
// Send CONNECT frame to initiate WebSocket handshake
String connectFrame = "CONNECT\naccept-version:1.2\n\n\u0000";
session.getBasicRemote().sendText(connectFrame);
logger.info("Sent CONNECT frame: " + connectFrame);

// Send SUBSCRIBE frame to subscribe to destination
String subscribeFrame = String.format("SUBSCRIBE\nid:sub-0\ndestination:%s\n\n\u0000", subscribeDestination);
session.getBasicRemote().sendText(subscribeFrame);
logger.info("Sent SUBSCRIBE frame: " + subscribeFrame);

} catch (Exception e) {
logger.error("Error during connection setup", e);
latch.countDown();
}
}

public void connect(String uri) {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();

ClientEndpointConfig config = ClientEndpointConfig.Builder.create()
.configurator(new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String, java.util.List<String>> headers) {
headers.put("Cookie", Collections.singletonList(cookie));
logger.info("Request headers: " + headers);
}
}).build();

try {
logger.info("Attempting to connect to: " + uri);
container.connectToServer(this, config, new URI(uri));

logger.info("Successfully connected to the WebSocket server.");

} catch (Exception e) {
logger.error("Connection failed: ", e);
}
}

@OnMessage
public void onMessage(String message) {
logger.info("Received message: " + message);

// Store the received message in the global map (keyed by message ID or custom identifier)
// Assuming the message contains a message-id field
String messageId = extractMessageId(message);
if (messageId != null) {
messageStore.put(messageId, message);
logger.info("Stored message with ID: " + messageId);
} else {
logger.warn("Received message without a valid message ID: " + message);
}
}

@OnClose
public void onClose(Session session, CloseReason closeReason) {
if (closeReason != null) {
logger.info("Connection closed: " + closeReason.getCloseCode() + " (" + closeReason.getReasonPhrase() + ")");
} else {
logger.info("Connection closed with no specific reason.");
}
latch.countDown();
}

@OnError
public void onError(Session session, Throwable throwable) {
logger.error("Error occurred: ", throwable);
if (session != null && session.isOpen()) {
try {
// Attempting to reconnect if needed
logger.info("Attempting to reconnect...");
connect("wss://your-websocket-url");
} catch (Exception e) {
logger.error("Error reconnecting: ", e);
}
}
latch.countDown();
}


public void sendMessage(String messageContent) {
if (session != null && session.isOpen()) {
try {
String sendFrame = String.format("SEND\ndestination:%s\ncontent-type:application/json\n\n%s\u0000", sendDestination, messageContent);
session.getBasicRemote().sendText(sendFrame);
logger.info("Sent message: " + sendFrame);
} catch (Exception e) {
logger.error("Error sending message: ", e);
}
} else {
logger.warn("Connection is not open. Unable to send message.");
session = null;
}
}

public void closeConnection() {
try {
if (session != null && session.isOpen()) {
session.close();
logger.info("WebSocket connection closed.");
}
} catch (Exception e) {
logger.error("Error closing connection", e);
}
}

// Method to extract the message ID from the received message (this is a placeholder)
private String extractMessageId(String message) {
try {
if (message.contains("message-id")) {
String[] parts = message.split("message-id:");
if (parts.length > 1) {
String messageId = parts[1].split("-")[0].trim(); // Adjust extraction logic as needed
return messageId;
}
}
} catch (Exception e) {
logger.error("Error extracting message ID", e);
}
return null;
}

public static Map<String, String> getMessageStore() {
return messageStore;
}

public Session getSession() {
return session;
}

public CountDownLatch getLatch() {
return latch;
}
}

0 comments on commit 126df14

Please sign in to comment.