1
\$\begingroup\$

This is the plain websocket code that connects with mobile app. Once we send a REST request from another service say B to our service A we send a websocket payload over the response. This runs in kubernetes pod. Could you suggest how to improve this?

@Component
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @Value("${ws.session.id}")
    private String sessionId;

    public void pushEvent(String sessionVariable, Object message) throws IOException {
        logger.info("Inside pushEvent..");
        String sessionHeaderData = null;
        boolean matchFound = false;
        for (WebSocketSession webSocketSession : SocketHandler.getSessions()) {
            sessionHeaderData= webSocketSession.getHandshakeHeaders().getFirst(sessionId);
            if (sessionHeaderData != null && sessionHeaderData.equals(sessionVariable)) {
                String payload = new Gson().toJson(message);
                logger.info("Payload:: {}", payload);
                webSocketSession.sendMessage(new TextMessage(payload));
                logger.info("Message sent successfully for session with ID:: {}", webSocketSession.getId());
                matchFound = true;
                break;
            }
        }
        if(!matchFound) {
            logger.error("No matching websocket session found ! for {}", sessionVariable);
        }
    }

Controller

@Service
public class WSWelcomeServiceImpl implements WSWelcomeService {
    
    private static final String TOTAL_ITEMS_QUANTITY = "Total items quantity";


    private static final Logger logger = LoggerFactory.getLogger(WSWelcomeServiceImpl.class);

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public ResponseEntity<Void> sendEvent(String accountNo, Event event) {
        Event pushEvent=null;
        logger.info("Triggering websocket  {} {} ", easeAccountNo, event);
        String eventCode = event.getEventTypeCode().toString();
        logger.info("Event received:: {}",eventCode);
        logger.info("Event Value Received:: {}", EventTypeCodeEnum.ITEM_QUANTITY.getValue());
        if(eventCode.equalsIgnoreCase(EventTypeCodeEnum.ITEM_QUANTITY.getValue())) {
            logger.info("Item Quantity Event received");
            pushEvent = pushItemQtyEvent(easeAccountNo, event);
        }else {
            pushEvent=event;
        }
        try {
            logger.info("Evenet Payload:: {}",new Gson().toJson(pushEvent));
            webSocketServer.pushEvent(String.valueOf(accountNo), pushEvent);
        } catch (Exception e) {
            logger.error("Exception occured during ws connection {}", e);
            throw new ClientCommunicationException(ErrorCodes.CLIENT_COMMUNICATION_ERROR.getErrorCode(),
                    ErrorCodes.CLIENT_COMMUNICATION_ERROR.getDescription());
        }
        logger.info("Exiting websocket controller");
        return new ResponseEntity<>(HttpStatus.valueOf(200));
    }
    private Event pushItemQtyEvent(String accountNo, Event event) {
        logger.info("Inside pushItemQtyEvent..");
        Event itemQtyEvent = new Event();
        itemQtyEvent.setAccountNo(accountNo.toString());
        itemQtyEvent.setEventTypeCode(EventTypeCodeEnum.ITEM_QUANTITY);
        itemQtyEvent.setEventTypeDesc(TOTAL_ITEMS_QUANTITY);
        QtyEvent qtyEvent = new QtyEvent();
        logger.info("Data Received:: {}", event.getData());
        logger.info("Item Quantity:: {}",event.getEventTypeDesc());
        qtyEvent.setTotalItemQty(BigDecimal.valueOf(Long.parseLong(event.getEventTypeDesc())));
        itemQtyEvent.setData(qtyEvent);
        return itemQtyEvent;
    }

}
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.