com.fivefaces.cloud.sms.TelstraSMSService Maven / Gradle / Ivy
package com.fivefaces.cloud.sms;
import com.fivefaces.cloud.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
@Profile("SMS_TELSTRA")
@Slf4j
@Service
public class TelstraSMSService implements SMSService{
private final RestTemplateBuilder restTemplateBuilder;
private final Utils utils;
private RestTemplate restTemplate;
private String lastUsedKey;
private String lastUsedSecret;
public TelstraSMSService(RestTemplateBuilder restTemplateBuilder, Utils utils) {
this.restTemplateBuilder = restTemplateBuilder;
this.utils = utils;
}
@Override
public void sendSms(String phoneNumber, String message) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(utils.getTelstraSenderUrl() + "/cgphttp/servlet/sendmsg")
.queryParam("text", message)
.queryParam("destination", phoneNumber);
URI url = builder.build(false).toUri();
log.info("Sending sms: " + url.toString());
try {
String response = getOrCreateRestTemplate().getForObject(url, String.class);
if (response != null && (response.charAt(0) != '0')) {
log.error("Sms was not sent. Cause: " + response);
} else
log.info("Sent Sms to " + phoneNumber);
} catch (Exception e) {
log.error("Sms was not sent. Cause: " + e.getMessage());
}
}
private RestTemplate getOrCreateRestTemplate() {
String currentKey = utils.getTelstraCurrentKey();
String currentSecret = utils.getTelstraCurrentSecret();
if (!StringUtils.equals(lastUsedKey, currentKey) || !StringUtils.equals(lastUsedSecret, currentSecret)) {
lastUsedKey = currentKey;
lastUsedSecret = currentSecret;
restTemplate = restTemplateBuilder.basicAuthentication(currentKey, currentSecret).build();
}
return restTemplate;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy