diff options
author | Anton Tananaev <anton.tananaev@gmail.com> | 2018-06-28 17:07:25 +1200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-06-28 17:07:25 +1200 |
commit | e849d3a56f55c83dc0ebed02165a124e30e22dbd (patch) | |
tree | 730e542145652ca1d06c64a6944dfa70e0b31b6b /src/org/traccar | |
parent | 4d6229c7daa4a7b8f28337c5eca9a422876c98b1 (diff) | |
parent | 14840af2abd9976b8f5634af8e77f4a7126dfac1 (diff) | |
download | trackermap-server-e849d3a56f55c83dc0ebed02165a124e30e22dbd.tar.gz trackermap-server-e849d3a56f55c83dc0ebed02165a124e30e22dbd.tar.bz2 trackermap-server-e849d3a56f55c83dc0ebed02165a124e30e22dbd.zip |
Merge pull request #3950 from Abyss777/notification_refactor
Notification refactor to allow custom "notificators"
Diffstat (limited to 'src/org/traccar')
17 files changed, 408 insertions, 160 deletions
diff --git a/src/org/traccar/BaseProtocol.java b/src/org/traccar/BaseProtocol.java index 1729edd54..62ee99946 100644 --- a/src/org/traccar/BaseProtocol.java +++ b/src/org/traccar/BaseProtocol.java @@ -91,18 +91,18 @@ public abstract class BaseProtocol implements Protocol { @Override public void sendTextCommand(String destAddress, Command command) throws Exception { - if (Context.getSmppManager() != null) { + if (Context.getSmsManager() != null) { if (command.getType().equals(Command.TYPE_CUSTOM)) { - Context.getSmppManager().sendMessageSync(destAddress, command.getString(Command.KEY_DATA), true); + Context.getSmsManager().sendMessageSync(destAddress, command.getString(Command.KEY_DATA), true); } else if (supportedTextCommands.contains(command.getType()) && textCommandEncoder != null) { - Context.getSmppManager().sendMessageSync(destAddress, + Context.getSmsManager().sendMessageSync(destAddress, (String) textCommandEncoder.encodeCommand(command), true); } else { throw new RuntimeException( "Command " + command.getType() + " is not supported in protocol " + getName()); } } else { - throw new RuntimeException("SMPP client is not enabled"); + throw new RuntimeException("SMS is not enabled"); } } diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 7224fd742..2afdde3b9 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -77,8 +77,9 @@ import org.traccar.geolocation.MozillaGeolocationProvider; import org.traccar.geolocation.OpenCellIdGeolocationProvider; import org.traccar.notification.EventForwarder; import org.traccar.notification.JsonTypeEventForwarder; +import org.traccar.notification.NotificatorManager; import org.traccar.reports.model.TripsConfig; -import org.traccar.smpp.SmppClient; +import org.traccar.sms.SmsManager; import org.traccar.web.WebServer; import javax.ws.rs.client.Client; @@ -206,6 +207,12 @@ public final class Context { return notificationManager; } + private static NotificatorManager notificatorManager; + + public static NotificatorManager getNotificatorManager() { + return notificatorManager; + } + private static VelocityEngine velocityEngine; public static VelocityEngine getVelocityEngine() { @@ -254,10 +261,10 @@ public final class Context { return statisticsManager; } - private static SmppClient smppClient; + private static SmsManager smsManager; - public static SmppClient getSmppManager() { - return smppClient; + public static SmsManager getSmsManager() { + return smsManager; } private static MotionEventHandler motionEventHandler; @@ -389,6 +396,15 @@ public final class Context { tripsConfig = initTripsConfig(); + if (config.getBoolean("sms.enable")) { + final String smsManagerClass = config.getString("sms.manager.class", "org.traccar.smpp.SmppClient"); + try { + smsManager = (SmsManager) Class.forName(smsManagerClass).newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + Log.warning("Error loading SMS Manager class : " + smsManagerClass, e); + } + } + if (config.getBoolean("event.enable")) { initEventsModule(); } @@ -407,10 +423,6 @@ public final class Context { statisticsManager = new StatisticsManager(); - if (config.getBoolean("sms.smpp.enable")) { - smppClient = new SmppClient(); - } - } private static void initGeolocationModule() { @@ -441,6 +453,7 @@ public final class Context { calendarManager = new CalendarManager(dataManager); maintenancesManager = new MaintenancesManager(dataManager); notificationManager = new NotificationManager(dataManager); + notificatorManager = new NotificatorManager(); Properties velocityProperties = new Properties(); velocityProperties.setProperty("file.resource.loader.path", Context.getConfig().getString("templates.rootPath", "templates") + "/"); diff --git a/src/org/traccar/api/resource/NotificationResource.java b/src/org/traccar/api/resource/NotificationResource.java index 540f02926..9631a52b7 100644 --- a/src/org/traccar/api/resource/NotificationResource.java +++ b/src/org/traccar/api/resource/NotificationResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,11 @@ package org.traccar.api.resource; import java.util.Collection; -import javax.mail.MessagingException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; +import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -31,13 +31,8 @@ import org.traccar.api.ExtendedObjectResource; import org.traccar.model.Event; import org.traccar.model.Notification; import org.traccar.model.Typed; -import org.traccar.notification.NotificationMail; -import org.traccar.notification.NotificationSms; +import org.traccar.notification.MessageException; -import com.cloudhopper.smpp.type.RecoverablePduException; -import com.cloudhopper.smpp.type.SmppChannelException; -import com.cloudhopper.smpp.type.SmppTimeoutException; -import com.cloudhopper.smpp.type.UnrecoverablePduException; @Path("notifications") @Produces(MediaType.APPLICATION_JSON) @@ -54,12 +49,27 @@ public class NotificationResource extends ExtendedObjectResource<Notification> { return Context.getNotificationManager().getAllNotificationTypes(); } + @GET + @Path("notificators") + public Collection<Typed> getNotificators() { + return Context.getNotificatorManager().getAllNotificatorTypes(); + } + @POST @Path("test") - public Response testMessage() throws MessagingException, RecoverablePduException, - UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { - NotificationMail.sendMailSync(getUserId(), new Event("test", 0), null); - NotificationSms.sendSmsSync(getUserId(), new Event("test", 0), null); + public Response testMessage() throws MessageException, InterruptedException { + for (Typed method : Context.getNotificatorManager().getAllNotificatorTypes()) { + Context.getNotificatorManager() + .getNotificator(method.getType()).sendSync(getUserId(), new Event("test", 0), null); + } + return Response.noContent().build(); + } + + @POST + @Path("test/{notificator}") + public Response testMessage(@PathParam("notificator") String notificator) + throws MessageException, InterruptedException { + Context.getNotificatorManager().getNotificator(notificator).sendSync(getUserId(), new Event("test", 0), null); return Response.noContent().build(); } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index 8ddced5f7..c11f05f9b 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -61,10 +61,10 @@ public class CommandsManager extends ExtendedObjectManager<Command> { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); protocol.sendTextCommand(phone, command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { - if (Context.getSmppManager() != null) { - Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); + if (Context.getSmsManager() != null) { + Context.getSmsManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else { - throw new RuntimeException("SMPP client is not enabled"); + throw new RuntimeException("SMS is not enabled"); } } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index 3bc048356..5dcb1d317 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -32,8 +32,6 @@ import org.traccar.model.Event; import org.traccar.model.Notification; import org.traccar.model.Position; import org.traccar.model.Typed; -import org.traccar.notification.NotificationMail; -import org.traccar.notification.NotificationSms; public class NotificationManager extends ExtendedObjectManager<Notification> { @@ -85,29 +83,16 @@ public class NotificationManager extends ExtendedObjectManager<Notification> { if (usersToForward != null) { usersToForward.add(userId); } - boolean sentWeb = false; - boolean sentMail = false; - boolean sentSms = Context.getSmppManager() == null; + final Set<String> notificators = new HashSet<>(); for (long notificationId : getEffectiveNotifications(userId, deviceId, event.getServerTime())) { Notification notification = getById(notificationId); if (getById(notificationId).getType().equals(event.getType())) { - if (!sentWeb && notification.getWeb()) { - Context.getConnectionManager().updateEvent(userId, event); - sentWeb = true; - } - if (!sentMail && notification.getMail()) { - NotificationMail.sendMailAsync(userId, event, position); - sentMail = true; - } - if (!sentSms && notification.getSms()) { - NotificationSms.sendSmsAsync(userId, event, position); - sentSms = true; - } - } - if (sentWeb && sentMail && sentSms) { - break; + notificators.addAll(notification.getNotificatorsTypes()); } } + for (String notificator : notificators) { + Context.getNotificatorManager().getNotificator(notificator).sendAsync(userId, event, position); + } } } if (Context.getEventForwarder() != null) { diff --git a/src/org/traccar/model/Notification.java b/src/org/traccar/model/Notification.java index cc80f2ae2..f1983a03a 100644 --- a/src/org/traccar/model/Notification.java +++ b/src/org/traccar/model/Notification.java @@ -15,6 +15,13 @@ */ package org.traccar.model; +import java.util.HashSet; +import java.util.Set; + +import org.traccar.database.QueryIgnore; + +import com.fasterxml.jackson.annotation.JsonIgnore; + public class Notification extends ScheduledModel { private boolean always; @@ -37,33 +44,29 @@ public class Notification extends ScheduledModel { this.type = type; } - private boolean web; - - public boolean getWeb() { - return web; - } - - public void setWeb(boolean web) { - this.web = web; - } - private boolean mail; + private String notificators; - public boolean getMail() { - return mail; + public String getNotificators() { + return notificators; } - public void setMail(boolean mail) { - this.mail = mail; + public void setNotificators(String transports) { + this.notificators = transports; } - private boolean sms; - public boolean getSms() { - return sms; + @JsonIgnore + @QueryIgnore + public Set<String> getNotificatorsTypes() { + final Set<String> result = new HashSet<>(); + if (notificators != null) { + final String[] transportsList = notificators.split(","); + for (String transport : transportsList) { + result.add(transport.trim()); + } + } + return result; } - public void setSms(boolean sms) { - this.sms = sms; - } } diff --git a/src/org/traccar/notification/MailMessage.java b/src/org/traccar/notification/FullMessage.java index 0fce43740..f66537c6e 100644 --- a/src/org/traccar/notification/MailMessage.java +++ b/src/org/traccar/notification/FullMessage.java @@ -16,12 +16,12 @@ */ package org.traccar.notification; -public class MailMessage { +public class FullMessage { private String subject; private String body; - public MailMessage(String subject, String body) { + public FullMessage(String subject, String body) { this.subject = subject; this.body = body; } diff --git a/src/org/traccar/notification/MessageException.java b/src/org/traccar/notification/MessageException.java new file mode 100644 index 000000000..ce4b9f6ee --- /dev/null +++ b/src/org/traccar/notification/MessageException.java @@ -0,0 +1,25 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +public class MessageException extends Exception { + + public MessageException(Throwable cause) { + super(cause); + } + +} diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java index 524153721..c011403c5 100644 --- a/src/org/traccar/notification/NotificationFormatter.java +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -88,18 +88,15 @@ public final class NotificationFormatter { return template; } - public static MailMessage formatMailMessage(long userId, Event event, Position position) { - String templatePath = Context.getConfig().getString("mail.templatesPath", "mail"); + public static FullMessage formatFullMessage(long userId, Event event, Position position) { VelocityContext velocityContext = prepareContext(userId, event, position); - String formattedMessage = formatMessage(velocityContext, userId, event, position, templatePath); + String formattedMessage = formatMessage(velocityContext, userId, event, position, "full"); - return new MailMessage((String) velocityContext.get("subject"), formattedMessage); + return new FullMessage((String) velocityContext.get("subject"), formattedMessage); } - public static String formatSmsMessage(long userId, Event event, Position position) { - String templatePath = Context.getConfig().getString("sms.templatesPath", "sms"); - - return formatMessage(null, userId, event, position, templatePath); + public static String formatShortMessage(long userId, Event event, Position position) { + return formatMessage(null, userId, event, position, "short"); } private static String formatMessage(VelocityContext vc, Long userId, Event event, Position position, diff --git a/src/org/traccar/notification/NotificationMail.java b/src/org/traccar/notification/NotificationMail.java index 6c81ecc79..c2ee67299 100644 --- a/src/org/traccar/notification/NotificationMail.java +++ b/src/org/traccar/notification/NotificationMail.java @@ -1,6 +1,6 @@ /* - * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org) - * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2017 - 2018 Andrey Kunitsyn (andrey@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,10 +32,7 @@ import org.traccar.model.Event; import org.traccar.model.Position; import org.traccar.model.User; -public final class NotificationMail { - - private NotificationMail() { - } +public final class NotificationMail extends Notificator { private static Properties getProperties(PropertiesProvider provider) { Properties properties = new Properties(); @@ -84,7 +81,8 @@ public final class NotificationMail { return properties; } - public static void sendMailSync(long userId, Event event, Position position) throws MessagingException { + @Override + public void sendSync(long userId, Event event, Position position) throws MessageException { User user = Context.getPermissionsManager().getUser(userId); Properties properties = null; @@ -103,40 +101,32 @@ public final class NotificationMail { MimeMessage message = new MimeMessage(session); - String from = properties.getProperty("mail.smtp.from"); - if (from != null) { - message.setFrom(new InternetAddress(from)); - } - - message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); - MailMessage mailMessage = NotificationFormatter.formatMailMessage(userId, event, position); - message.setSubject(mailMessage.getSubject()); - message.setSentDate(new Date()); - message.setContent(mailMessage.getBody(), "text/html; charset=utf-8"); - - Transport transport = session.getTransport(); try { - Context.getStatisticsManager().registerMail(); - transport.connect( - properties.getProperty("mail.smtp.host"), - properties.getProperty("mail.smtp.username"), - properties.getProperty("mail.smtp.password")); - transport.sendMessage(message, message.getAllRecipients()); - } finally { - transport.close(); - } - } + String from = properties.getProperty("mail.smtp.from"); + if (from != null) { + message.setFrom(new InternetAddress(from)); + } - public static void sendMailAsync(final long userId, final Event event, final Position position) { - new Thread(new Runnable() { - public void run() { - try { - sendMailSync(userId, event, position); - } catch (MessagingException error) { - Log.warning(error); - } + message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); + FullMessage fullMessage = NotificationFormatter.formatFullMessage(userId, event, position); + message.setSubject(fullMessage.getSubject()); + message.setSentDate(new Date()); + message.setContent(fullMessage.getBody(), "text/html; charset=utf-8"); + + Transport transport = session.getTransport(); + try { + Context.getStatisticsManager().registerMail(); + transport.connect( + properties.getProperty("mail.smtp.host"), + properties.getProperty("mail.smtp.username"), + properties.getProperty("mail.smtp.password")); + transport.sendMessage(message, message.getAllRecipients()); + } finally { + transport.close(); } - }).start(); + } catch (MessagingException e) { + throw new MessageException(e); + } } } diff --git a/src/org/traccar/notification/NotificationNull.java b/src/org/traccar/notification/NotificationNull.java new file mode 100644 index 000000000..3ee954c24 --- /dev/null +++ b/src/org/traccar/notification/NotificationNull.java @@ -0,0 +1,34 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +import org.traccar.helper.Log; +import org.traccar.model.Event; +import org.traccar.model.Position; + +public final class NotificationNull extends Notificator { + + @Override + public void sendAsync(long userId, Event event, Position position) { + Log.warning("You are using null notificatior, please check your configuration, notification not sent"); + } + + @Override + public void sendSync(long userId, Event event, Position position) { + Log.warning("You are using null notificatior, please check your configuration, notification not sent"); + } +} diff --git a/src/org/traccar/notification/NotificationSms.java b/src/org/traccar/notification/NotificationSms.java index 8c0265af4..ed651ac11 100644 --- a/src/org/traccar/notification/NotificationSms.java +++ b/src/org/traccar/notification/NotificationSms.java @@ -1,6 +1,6 @@ /* - * Copyright 2017 Anton Tananaev (anton@traccar.org) - * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2017 - 2018 Andrey Kunitsyn (andrey@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,33 +20,38 @@ import org.traccar.Context; import org.traccar.model.Event; import org.traccar.model.Position; import org.traccar.model.User; +import org.traccar.sms.SmsManager; -import com.cloudhopper.smpp.type.RecoverablePduException; -import com.cloudhopper.smpp.type.SmppChannelException; -import com.cloudhopper.smpp.type.SmppTimeoutException; -import com.cloudhopper.smpp.type.UnrecoverablePduException; +public final class NotificationSms extends Notificator { -public final class NotificationSms { + private final SmsManager smsManager; - private NotificationSms() { + public NotificationSms() throws ClassNotFoundException, InstantiationException, IllegalAccessException { + final String smsClass = Context.getConfig().getString("notificator.sms.manager.class", ""); + if (smsClass.length() > 0) { + smsManager = (SmsManager) Class.forName(smsClass).newInstance(); + } else { + smsManager = Context.getSmsManager(); + } } - public static void sendSmsAsync(long userId, Event event, Position position) { - User user = Context.getPermissionsManager().getUser(userId); - if (Context.getSmppManager() != null && user.getPhone() != null) { + @Override + public void sendAsync(long userId, Event event, Position position) { + final User user = Context.getPermissionsManager().getUser(userId); + if (user.getPhone() != null) { Context.getStatisticsManager().registerSms(); - Context.getSmppManager().sendMessageAsync(user.getPhone(), - NotificationFormatter.formatSmsMessage(userId, event, position), false); + smsManager.sendMessageAsync(user.getPhone(), + NotificationFormatter.formatShortMessage(userId, event, position), false); } } - public static void sendSmsSync(long userId, Event event, Position position) throws RecoverablePduException, - UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { - User user = Context.getPermissionsManager().getUser(userId); - if (Context.getSmppManager() != null && user.getPhone() != null) { + @Override + public void sendSync(long userId, Event event, Position position) throws MessageException, InterruptedException { + final User user = Context.getPermissionsManager().getUser(userId); + if (user.getPhone() != null) { Context.getStatisticsManager().registerSms(); - Context.getSmppManager().sendMessageSync(user.getPhone(), - NotificationFormatter.formatSmsMessage(userId, event, position), false); + smsManager.sendMessageSync(user.getPhone(), + NotificationFormatter.formatShortMessage(userId, event, position), false); } } } diff --git a/src/org/traccar/notification/NotificationWeb.java b/src/org/traccar/notification/NotificationWeb.java new file mode 100644 index 000000000..afc401d24 --- /dev/null +++ b/src/org/traccar/notification/NotificationWeb.java @@ -0,0 +1,30 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +import org.traccar.Context; +import org.traccar.model.Event; +import org.traccar.model.Position; + +public final class NotificationWeb extends Notificator { + + @Override + public void sendSync(long userId, Event event, Position position) { + Context.getConnectionManager().updateEvent(userId, event); + } + +} diff --git a/src/org/traccar/notification/Notificator.java b/src/org/traccar/notification/Notificator.java new file mode 100644 index 000000000..d912b445d --- /dev/null +++ b/src/org/traccar/notification/Notificator.java @@ -0,0 +1,40 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +import org.traccar.helper.Log; +import org.traccar.model.Event; +import org.traccar.model.Position; + +public abstract class Notificator { + + public void sendAsync(final long userId, final Event event, final Position position) { + new Thread(new Runnable() { + public void run() { + try { + sendSync(userId, event, position); + } catch (MessageException | InterruptedException error) { + Log.warning(error); + } + } + }).start(); + } + + public abstract void sendSync(long userId, Event event, Position position) + throws MessageException, InterruptedException; + +} diff --git a/src/org/traccar/notification/NotificatorManager.java b/src/org/traccar/notification/NotificatorManager.java new file mode 100644 index 000000000..147de47d3 --- /dev/null +++ b/src/org/traccar/notification/NotificatorManager.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.notification; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.traccar.Context; +import org.traccar.helper.Log; +import org.traccar.model.Typed; + +public final class NotificatorManager { + + private static final String DEFAULT_WEB_NOTIFICATOR = "org.traccar.notification.NotificationWeb"; + private static final String DEFAULT_MAIL_NOTIFICATOR = "org.traccar.notification.NotificationMail"; + private static final String DEFAULT_SMS_NOTIFICATOR = "org.traccar.notification.NotificationSms"; + + private final Map<String, Notificator> notificators = new HashMap<>(); + private static final Notificator NULL_NOTIFICATOR = new NotificationNull(); + + public NotificatorManager() { + final String[] types = Context.getConfig().getString("notificator.types", "").split(","); + for (String type : types) { + String defaultNotificator = ""; + switch (type) { + case "web": + defaultNotificator = DEFAULT_WEB_NOTIFICATOR; + break; + case "mail": + defaultNotificator = DEFAULT_MAIL_NOTIFICATOR; + break; + case "sms": + defaultNotificator = DEFAULT_SMS_NOTIFICATOR; + break; + default: + break; + } + final String className = Context.getConfig() + .getString("notificator." + type + ".class", defaultNotificator); + try { + notificators.put(type, (Notificator) Class.forName(className).newInstance()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + Log.error("Unable to load notificator class for " + type + " " + className + " " + e.getMessage()); + } + } + } + + public Notificator getNotificator(String type) { + final Notificator notificator = notificators.get(type); + if (notificator == null) { + Log.error("No notificator configured for type : " + type); + return NULL_NOTIFICATOR; + } + return notificator; + } + + public Set<Typed> getAllNotificatorTypes() { + Set<Typed> result = new HashSet<>(); + for (String notificator : notificators.keySet()) { + result.add(new Typed(notificator)); + } + return result; + } + +} diff --git a/src/org/traccar/smpp/SmppClient.java b/src/org/traccar/smpp/SmppClient.java index 967eed82c..ddda4cb4f 100644 --- a/src/org/traccar/smpp/SmppClient.java +++ b/src/org/traccar/smpp/SmppClient.java @@ -25,6 +25,8 @@ import java.util.concurrent.TimeUnit; import org.traccar.Context; import org.traccar.helper.Log; +import org.traccar.notification.MessageException; +import org.traccar.sms.SmsManager; import com.cloudhopper.commons.charset.CharsetUtil; import com.cloudhopper.smpp.SmppBindType; @@ -42,7 +44,7 @@ import com.cloudhopper.smpp.type.SmppChannelException; import com.cloudhopper.smpp.type.SmppTimeoutException; import com.cloudhopper.smpp.type.UnrecoverablePduException; -public class SmppClient { +public class SmppClient implements SmsManager { private SmppSessionConfiguration sessionConfig = new SmppSessionConfiguration(); private SmppSession smppSession; @@ -212,46 +214,52 @@ public class SmppClient { } } + @Override public synchronized void sendMessageSync(String destAddress, String message, boolean command) - throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, - InterruptedException, IllegalStateException { + throws MessageException, InterruptedException, IllegalStateException { if (getSession() != null && getSession().isBound()) { - SubmitSm submit = new SubmitSm(); - byte[] textBytes; - textBytes = CharsetUtil.encode(message, command ? commandsCharsetName : notificationsCharsetName); - submit.setDataCoding(command ? commandsDataCoding : notificationsDataCoding); - if (requestDlr) { - submit.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED); - } + try { + SubmitSm submit = new SubmitSm(); + byte[] textBytes; + textBytes = CharsetUtil.encode(message, command ? commandsCharsetName : notificationsCharsetName); + submit.setDataCoding(command ? commandsDataCoding : notificationsDataCoding); + if (requestDlr) { + submit.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED); + } - if (textBytes != null && textBytes.length > 255) { - submit.addOptionalParameter(new Tlv(SmppConstants.TAG_MESSAGE_PAYLOAD, textBytes, "message_payload")); - } else { - submit.setShortMessage(textBytes); - } + if (textBytes != null && textBytes.length > 255) { + submit.addOptionalParameter(new Tlv(SmppConstants.TAG_MESSAGE_PAYLOAD, textBytes, + "message_payload")); + } else { + submit.setShortMessage(textBytes); + } - submit.setSourceAddress(command ? new Address(commandSourceTon, commandSourceNpi, commandSourceAddress) - : new Address(sourceTon, sourceNpi, sourceAddress)); - submit.setDestAddress(new Address(destTon, destNpi, destAddress)); - SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); - if (submitResponce.getCommandStatus() == SmppConstants.STATUS_OK) { - Log.debug("SMS submitted, message id: " + submitResponce.getMessageId()); - } else { - throw new IllegalStateException(submitResponce.getResultMessage()); + submit.setSourceAddress(command ? new Address(commandSourceTon, commandSourceNpi, commandSourceAddress) + : new Address(sourceTon, sourceNpi, sourceAddress)); + submit.setDestAddress(new Address(destTon, destNpi, destAddress)); + SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); + if (submitResponce.getCommandStatus() == SmppConstants.STATUS_OK) { + Log.debug("SMS submitted, message id: " + submitResponce.getMessageId()); + } else { + throw new IllegalStateException(submitResponce.getResultMessage()); + } + } catch (SmppChannelException | RecoverablePduException + | SmppTimeoutException | UnrecoverablePduException error) { + throw new MessageException(error); } } else { - throw new SmppChannelException("SMPP session is not connected"); + throw new MessageException(new SmppChannelException("SMPP session is not connected")); } } + @Override public void sendMessageAsync(final String destAddress, final String message, final boolean command) { executorService.execute(new Runnable() { @Override public void run() { try { sendMessageSync(destAddress, message, command); - } catch (InterruptedException | RecoverablePduException | UnrecoverablePduException - | SmppTimeoutException | SmppChannelException | IllegalStateException error) { + } catch (MessageException | InterruptedException | IllegalStateException error) { Log.warning(error); } } diff --git a/src/org/traccar/sms/SmsManager.java b/src/org/traccar/sms/SmsManager.java new file mode 100644 index 000000000..4bc4bd009 --- /dev/null +++ b/src/org/traccar/sms/SmsManager.java @@ -0,0 +1,27 @@ +/* + * Copyright 2018 Anton Tananaev (anton@traccar.org) + * Copyright 2018 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.sms; + +import org.traccar.notification.MessageException; + +public interface SmsManager { + + void sendMessageSync(String destAddress, String message, boolean command) + throws InterruptedException, MessageException; + void sendMessageAsync(final String destAddress, final String message, final boolean command); + +} |