0

Below is my SMS class

public class SMS implements Notification {

    private static final Logger LOG = LogManager.getLogger(SMS.class);
    private static final Properties PROP = PropertyReader.loadProperties(PropertyFile.OTP);
    private static final String SMS_API_URL_PROP = "otp.sms.common.api.url";
    private static final String SMS_PROVIDER = "otp.sms.provider.name";

    private static final String MOBILE_NUMBER_FIELD = "MobileNumber";
    private static final String MESSAGE_FIELD = "Message";
    private static final String PROVIDER_FIELD = "Provider";
    private static final String CALLER_URL_FIELD = "CallerUrl";
    private static final String PROVIDER_VALUE = PROP.getProperty(SMS_PROVIDER);
    private static final String REQUEST_DATA_FIELD = "RequestData";

    private String recipient;
    private String smsTemplate;
    private String[] smsParams;
    private String callerUrl;
    private String requestId;
    private String channel;

    public SMS(String recipient, String smsTemplate, String[] smsParams, String callerUrl, String requestId, String channel) {
        this.recipient = recipient;
        this.smsTemplate = smsTemplate;
        this.smsParams = smsParams;
        this.callerUrl = callerUrl;
        this.requestId = requestId;
        this.channel = channel;
    }

    public SMS(String recipient, String smsTemplate, String... smsParams) {
        this.recipient = recipient;
        this.smsTemplate = smsTemplate;
        this.smsParams = smsParams;
    }

//    public SMS(String recipient, String smsTemplate, String callerUrl, String requestId, String channel,
//            String... smsParams) {
//        this.recipient = recipient;
//        this.smsTemplate = smsTemplate;
//        this.smsParams = smsParams;
//        this.callerUrl = callerUrl;
//        this.requestId = requestId;
//        this.channel = channel;
//    }

    @Override
    public boolean send() throws IllegalNotificationArgumentException {
        String smsText = String.format(this.smsTemplate, (Object[]) this.smsParams);
        return sendSMS(this.recipient, smsText, this.callerUrl, this.requestId, this.channel);
    }

    /**
     * Sends an SMS to this mobile number
     *
     * @param recipient
     * @param text
     * @return
     * @throws IllegalNotificationArgumentException
     */
    private boolean sendSMS(String recipient, String text, String callerUrl, String requestId, String channel)
            throws IllegalNotificationArgumentException {
        LOG.debug("Sending SMS notification to: " + recipient);
        System.out.println("SMS DATA : "+ recipient + " "  +text + " " +callerUrl + " " + requestId + " " +channel + " ");

        try {
            if (StringUtils.isNotBlank(recipient) && StringUtils.isNotBlank(text)) {

                submitShortMessage(recipient, text, callerUrl, requestId, channel);
                return true;
            } else {
                LOG.warn("Throwing IllegalNotificationArgumentException");
                throw new IllegalNotificationArgumentException(
                        "Illegal Notification Arguments in sendSMS()");
            }
        } catch (IOException | UserStoreException e) {
            LOG.error("Failed to invoke SMS API: " + e.getMessage());
        }
        return false;
    }

    /**
     * submitShortMessage
     *
     * @param mobile
     * @param text
     * @throws IOException
     */
    private void submitShortMessage(String mobile, String text, String callerUrl, String requestId, String channel)
            throws IOException, UserStoreException {
        // LOG.info("mobile : " + mobile + ", text : " + text);
        // CloseableHttpClient apacheHttpClient =
        // HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        CloseableHttpClient apacheHttpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .build();

        try {
            String smsApiUrl = PROP.getProperty(SMS_API_URL_PROP);
            if(callerUrl == null){
                System.out.println("CALLER URL NULLL");
                callerUrl = "sms-tigo-trust-lk";
            }
            JsonNode sendOtpJson = getSendOTPJson(mobile, text, callerUrl);
            LOG.debug("SMS API url: " + smsApiUrl);
            LOG.debug("Send sms json: " + sendOtpJson);
            HttpPost httpPost = new HttpPost(smsApiUrl);

            // Add headers
            httpPost.setHeader("Channel", channel);
            httpPost.setHeader("RequestId", requestId);
            httpPost.setHeader("Content-Type", "application/json");

            // Set request body
            StringEntity entity = new StringEntity(sendOtpJson.toString());
            httpPost.setEntity(entity);
            System.out.println("HTTP POSTTT :"+ httpPost);

           CloseableHttpResponse response = HttpClient.post(apacheHttpClient, httpPost);
            System.out.println("RESPONSEEEE :"+ response);
            //CloseableHttpResponse response = apacheHttpClient.execute(httpPost);

            String stringResponseEntity = null;
            if (response != null) {
                HttpEntity responseEntity = response.getEntity();
                stringResponseEntity = EntityUtils.toString(responseEntity);
            }
            System.out.println("STRING RESPONSE ENTITY :"+ stringResponseEntity);
            try {
                if (response != null
                        && response.getStatusLine().getStatusCode() == APIConstant.SUCCESS_STATUS) {
                    LOG.debug("Message submitted: " + stringResponseEntity);
                    LOG.info("SMS notification successfully sent to: " + mobile);
                } else {
                    throw new IOException(stringResponseEntity);
                }

            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } finally {
            apacheHttpClient.close();
        }
    }

    /**
     * @param recipient
     * @param message
     * @return JsonNode - POST otp send JSON
     */
    private JsonNode getSendOTPJson(String recipient, String message, String callerUrl) {

        ObjectMapper mapper = new ObjectMapper(); // creates mapper object
        JsonNode rootNode = mapper.createObjectNode(); // creates root node
        JsonNode requestDataNode = mapper.createObjectNode(); // creates root node

        ((ObjectNode) requestDataNode).put(MOBILE_NUMBER_FIELD, recipient);
        ((ObjectNode) requestDataNode).put(MESSAGE_FIELD, message);
        ((ObjectNode) requestDataNode).put(PROVIDER_FIELD, PROVIDER_VALUE);
        ((ObjectNode) requestDataNode).put(CALLER_URL_FIELD, callerUrl);

        // add OTP request fields
        ((ObjectNode) rootNode).put(REQUEST_DATA_FIELD, requestDataNode);

        return rootNode;

    }

}

What I need is to send the the mobile number, caller url, message and provider values in the format below to an api created using wso2 EI.

{
    "RequestData": {
        "MobileNumber": "255756583454",
        "Message": "Ndugu mteja sasa unaweza jiunga na SIMbanking kwa kupiga *150*03#. Namba yako ya siri ni 4145",
        "Provider": "INFOBIP",
        "CallerUrl": null
    }
}

When I log the request body in the api, I get the below request ``{"text":"{"RequestData":{"MobileNumber":"255756583444","Message":"Ndugu mteja, namba yako ya SimBanking imebadilishwa kutoka 255756583444 kwenda 255756583854. Kwa maelezo zaidi piga 0755197700.","Provider":"INFOBIP","CallerUrl":"sms-tigo-trust-lk"}}"} Why does it get wrapped in a key named "text"? How to fix it? Please help.

1 Answer 1

0

The reason why your request body is getting wrapped in a key named "text" is likely due to how it's being serialized when you're converting your JSON object to a string.

Can you try this?

// Set request body without unnecessary wrapping
StringEntity entity = new StringEntity(sendOtpJson.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.