package za.co.taulite.tools.smppclient.services;
|
|
import org.jsmpp.InvalidResponseException;
|
import org.jsmpp.PDUException;
|
import org.jsmpp.bean.*;
|
import org.jsmpp.extra.NegativeResponseException;
|
import org.jsmpp.extra.ProcessRequestException;
|
import org.jsmpp.extra.ResponseTimeoutException;
|
import org.jsmpp.extra.SessionState;
|
import org.jsmpp.session.*;
|
import org.jsmpp.util.*;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.context.ApplicationEventPublisher;
|
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.shell.Availability;
|
import org.springframework.stereotype.Component;
|
|
import javax.annotation.PostConstruct;
|
import javax.annotation.PreDestroy;
|
import java.io.IOException;
|
import java.nio.charset.StandardCharsets;
|
import java.util.Date;
|
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.Executors;
|
import java.util.concurrent.ThreadPoolExecutor;
|
|
@Component
|
public class SmppService {
|
|
private static final Logger logger = LoggerFactory.getLogger(SmppService.class);
|
private static final TimeFormatter TIME_FORMATTER = new AbsoluteTimeFormatter();
|
private static final MessageIDGenerator MESSAGE_ID_GENERATOR = new RandomMessageIDGenerator();
|
|
private ExecutorService executorService = Executors.newFixedThreadPool(10);
|
private SMPPSession session = new SMPPSession();
|
|
@PostConstruct
|
public void init() {
|
session.setMessageReceiverListener(new MessageReceiverListener() {
|
public void onAcceptDeliverSm(DeliverSm deliverSm)
|
throws ProcessRequestException {
|
if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) {
|
//counter.incrementAndGet();
|
// delivery receipt
|
try {
|
DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt();
|
// long id = Long.parseLong(delReceipt.getId()) & 0xffffffff;
|
// String messageId = Long.toString(id, 16).toUpperCase();
|
logger.info("Receiving delivery receipt for message '{}' : {}", delReceipt.getId(), delReceipt);
|
} catch (InvalidDeliveryReceiptException e) {
|
logger.error("Failed getting delivery receipt", e);
|
}
|
} else {
|
// regular short message
|
logger.info("Receiving message : {}", new String(deliverSm.getShortMessage()));
|
}
|
}
|
|
public void onAcceptAlertNotification(AlertNotification alertNotification) {
|
logger.info("Receiving alert_notification");
|
}
|
|
public DataSmResult onAcceptDataSm(DataSm dataSm, Session source)
|
throws ProcessRequestException {
|
MessageId messageId = MESSAGE_ID_GENERATOR.newMessageId();
|
logger.info("Receiving data_sm, generated message id {}", messageId.getValue());
|
return new DataSmResult(messageId, new OptionalParameter[]{});
|
}
|
});
|
}
|
|
public void connect(String sysId, String password, String host, int port) {
|
try {
|
logger.info("Connecting");
|
// String systemId = session.connectAndBind("test-sms-a.umsg.co.za", 2775, new BindParameter(BindType.BIND_TX, "u34853", "hecHxMKJ", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));
|
// String systemId = session.connectAndBind("localhost", 2776, new BindParameter(BindType.BIND_TRX, "smppclient1", "password", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));
|
String systemId = session.connectAndBind(host, port, new BindParameter(BindType.BIND_TRX, sysId, password, "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));
|
logger.info("Connected with SMSC with system id {}", systemId);
|
} catch (IOException e) {
|
logger.error("Failed connect and bind to host", e);
|
}
|
}
|
|
@PreDestroy
|
public void disconnect() {
|
if (session != null) {
|
session.unbindAndClose();
|
}
|
}
|
|
public String status() {
|
return String.valueOf(session.getSessionState());
|
}
|
|
public Availability availabilityCheck() {
|
return session.getSessionState() == SessionState.BOUND_TRX
|
? Availability.available()
|
: Availability.unavailable(String.format("Session in state [%s]", session.getSessionState()));
|
}
|
|
public void send(String anumber, String bnumber, String message) {
|
executorService.submit(() -> {
|
try {
|
SubmitSmResult submitSmResult = session.submitShortMessage("cp",
|
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, anumber,
|
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, bnumber,
|
new ESMClass(), (byte)0, (byte)1, TIME_FORMATTER.format(new Date()), null,
|
new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE), (byte)0, new GeneralDataCoding(Alphabet.ALPHA_DEFAULT), (byte)0,
|
message.getBytes(StandardCharsets.US_ASCII));
|
String messageId = submitSmResult.getMessageId();
|
logger.info("Message submitted, message_id is {}", messageId);
|
} catch (PDUException e) {
|
// Invalid PDU parameter
|
logger.error("Invalid PDU parameter", e);
|
} catch (ResponseTimeoutException e) {
|
// Response timeout
|
logger.error("Response timeout", e);
|
} catch (InvalidResponseException e) {
|
// Invalid response
|
logger.error("Receive invalid response", e);
|
} catch (NegativeResponseException e) {
|
// Receiving negative response (non-zero command_status)
|
logger.error("Receive negative response", e);
|
} catch (IOException e) {
|
logger.error("IO error occurred", e);
|
}
|
});
|
}
|
|
/*
|
@Autowired
|
private ApplicationEventPublisher applicationEventPublisher;
|
|
@Autowired
|
private AuthApi authApi;
|
|
@Autowired
|
private ApiClient apiClient;
|
|
private User user;
|
private TokenRsp auth;
|
|
public User getUser() {
|
return user;
|
}
|
|
public String getAccessToken() {
|
return auth.getAccessToken();
|
}
|
|
@Scheduled(fixedRate = 30000)
|
public void checkToken() {
|
if (!hasToken()) {
|
return;
|
}
|
|
if (!isTokenValid()) {
|
if (!refreshToken()) {
|
setAuth(null);
|
setUser(null);
|
}
|
}
|
}
|
|
public boolean isLoggedIn() {
|
return hasToken() && user != null && isTokenValid();
|
}
|
|
public boolean hasToken() {
|
return auth != null;
|
}
|
|
public boolean isTokenValid() {
|
return auth != null && auth.getExpiry() > System.currentTimeMillis() - 10000;
|
}
|
|
public boolean refreshToken() {
|
if (!hasToken()) {
|
return false;
|
}
|
|
try {
|
auth = authApi.refreshToken(new RefreshReq().clientId("gateway").refreshToken(auth.getRefreshToken()));
|
if (auth.getError() != null) {
|
return false;
|
}
|
loadMe();
|
return true;
|
} catch (ApiException ex) {
|
return false;
|
}
|
}
|
|
public String whoami() {
|
if (!isLoggedIn() || user == null) {
|
return "Anonymous";
|
}
|
return String.format("%s (%s)", user.getUsername(), user.getEmail());
|
}
|
|
public void logout() {
|
setAuth(null);
|
setUser(null);
|
}
|
|
private void setAuth(TokenRsp auth) {
|
this.auth = auth;
|
}
|
|
private void setUser(User user) {
|
this.user = user;
|
applicationEventPublisher.publishEvent(new MSLoginEvent(this, user == null ? null : user.getUsername()));
|
}
|
|
public void login(String username, String password) throws ApiException {
|
auth = authApi.login(new TokenReq().clientId("gateway").username(username).password(password));
|
if (auth.getError() != null) {
|
throw new ApiException(auth.getError());
|
}
|
apiClient.setAccessToken(auth.getAccessToken());
|
loadMe();
|
}
|
|
public void loadMe() throws ApiException {
|
setUser(authApi.whoami());
|
}
|
|
public Availability availabilityCheck() {
|
var message = "You are not logged in";
|
if (hasToken() && !isTokenValid()) {
|
message = "Session has expired, please login again";
|
}
|
return isLoggedIn()
|
? Availability.available()
|
: Availability.unavailable(message);
|
}
|
*/
|
}
|