Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Sender {
- fun send(send: Send, message: String, to: String) {
- send.send(to, message)
- }
- }
- interface Send {
- fun send(to: String, message: String)
- }
- class SendSMS(private val phoneValidator: PhoneValidator,
- private val smpp: SMPPProxy,
- private val username: String,
- private val password: String) : Send {
- override fun send(to: String, message: String) {
- if (!phoneValidator.isValid(to)) {
- throw NoPhoneNumber(invalidPhone = to)
- }
- try {
- smpp.openConnection(username, password)
- smpp.send(to, message, null, "15")
- smpp.closeConnection()
- } catch (ex: Exception) {
- try {
- smpp.closeConnection()
- } catch (ex: Exception) {
- } finally {
- throw SendSMSException(ex.message ?: "unknown message")
- }
- }
- }
- }
- class SendEmail(private val emailConnection: SendMailConnection) : Send {
- var subject: String = ""
- override fun send(to: String, message: String) {
- if (subject.isEmpty()) {
- throw RequiredSubjectEmail()
- }
- try {
- emailConnection.prepareMessage(to, message, subject)
- emailConnection.send()
- emailConnection.close()
- } catch (ex: Exception) {
- try {
- emailConnection.close()
- } catch (ex: Exception) {
- } finally {
- throw SendEmailException(ex.message ?: "unknown message")
- }
- }
- }
- }
- class SMPPProxy(private val ip: String,
- private val port: String) {
- val smpp: SMPP by lazy {
- SMPP(ip, port)
- }
- fun openConnection(username: String, password: String) = smpp.openConnection(username, password)
- fun closeConnection() = smpp.closeConnection()
- fun send(to: String, message: String, a: String?, s: String) {
- smpp.send(to, message, a, s)
- }
- }
- sealed class SendException(message: String = "") : Exception(message)
- class SendEmailException(message: String) : SendException(message)
- class RequiredSubjectEmail : SendException()
- class NoPhoneNumber(invalidPhone: String) : SendException("$invalidPhone is not a phone number")
- class SendSMSException(message: String) : SendException(message)
- fun main(vararg arg: String) {
- try {
- val smpp = SMPPProxy("192.168.1.4", "4301")
- val emailConnection = SendMailConnection("mail.myserver.com")
- val sms = SendSMS(PhoneValidator(), smpp, "yourusername", "yourpassword")
- val email = SendEmail(emailConnection)
- val sender = Sender()
- sender.send(sms, "Message", "675848584")
- email.subject = "Subject"
- sender.send(email, "Message", "tonilopezmr@gmail.com")
- } catch (ex: SendException) {
- ex.printStackTrace()
- }
- }
Add Comment
Please, Sign In to add comment