Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Major refactor of notification infrastructure and various other changes (breaking DB schema change migration included):

Rich Turner31fd201c0294
diff --git a/client/src/main/java/org/openremote/app/client/admin/DeviceNotificationTokenMapper.java b/client/src/main/java/org/openremote/app/client/admin/DeviceNotificationTokenMapper.java
deleted file mode 100644
index f48b9139d..000000000
--- a/client/src/main/java/org/openremote/app/client/admin/DeviceNotificationTokenMapper.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.app.client.admin;
-
-import com.github.nmorel.gwtjackson.client.ObjectMapper;
-import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
-import org.openremote.app.client.interop.jackson.DefaultJsonMixin;
-import org.openremote.app.client.rest.EntityReader;
-import org.openremote.model.notification.DeviceNotificationToken;
-
-import java.util.List;
-
-@JsonMixIns({@JsonMixIns.JsonMixIn(target = DeviceNotificationToken.class, mixIn = DefaultJsonMixin.class)})
-public interface DeviceNotificationTokenMapper
- extends ObjectMapper<List<DeviceNotificationToken>>,
- EntityReader<List<DeviceNotificationToken>> {
-}
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEdit.java b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEdit.java
index 2a89a121c..c0b0a91fc 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEdit.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEdit.java
@@ -21,9 +21,6 @@ package org.openremote.app.client.admin.users.edit;
import org.openremote.app.client.admin.AdminContent;
import org.openremote.app.client.admin.users.AbstractAdminUsersPlace;
-import org.openremote.model.notification.DeviceNotificationToken;
-
-import java.util.List;
public interface AdminUserEdit extends AdminContent {
@@ -33,10 +30,6 @@ public interface AdminUserEdit extends AdminContent {
void onRoleAssigned(String id, boolean assigned);
- void onDeviceRegistrationDelete(DeviceNotificationToken.Id id);
-
- void onDeviceRegistrationsRefresh();
-
void create();
void update();
@@ -100,10 +93,6 @@ public interface AdminUserEdit extends AdminContent {
void toggleRoleAssigned(String id, boolean assigned);
- void setDeviceRegistrations(List<DeviceNotificationToken> deviceNotificationTokens);
-
- void removeDeviceRegistration(DeviceNotificationToken.Id id);
-
void enableCreate(boolean enable);
void enableUpdate(boolean enable);
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditActivity.java b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditActivity.java
index 03c4089c1..886007e2e 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditActivity.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditActivity.java
@@ -31,7 +31,6 @@ import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.http.ConstraintViolation;
import org.openremote.model.interop.Consumer;
import org.openremote.model.interop.Runnable;
-import org.openremote.model.notification.DeviceNotificationToken;
import org.openremote.model.notification.NotificationResource;
import org.openremote.model.security.Credential;
import org.openremote.model.security.Role;
@@ -54,7 +53,6 @@ public class AdminUserEditActivity
final protected CredentialMapper credentialMapper;
final protected RoleArrayMapper roleArrayMapper;
final protected NotificationResource notificationResource;
- final protected DeviceNotificationTokenMapper deviceNotificationTokenMapper;
final protected Consumer<ConstraintViolation[]> validationErrorHandler;
protected AdminUserEditPlace place;
@@ -72,8 +70,7 @@ public class AdminUserEditActivity
UserMapper userMapper,
CredentialMapper credentialMapper,
RoleArrayMapper roleArrayMapper,
- NotificationResource notificationResource,
- DeviceNotificationTokenMapper deviceNotificationTokenMapper) {
+ NotificationResource notificationResource) {
super(adminView, adminNavigationPresenter, view);
this.environment = environment;
this.userResource = userResource;
@@ -81,7 +78,6 @@ public class AdminUserEditActivity
this.credentialMapper = credentialMapper;
this.roleArrayMapper = roleArrayMapper;
this.notificationResource = notificationResource;
- this.deviceNotificationTokenMapper = deviceNotificationTokenMapper;
this.validationErrorHandler = violations -> {
for (ConstraintViolation violation : violations) {
if (violation.getConstraintType() == ConstraintViolation.Type.CONFLICT) {
@@ -268,25 +264,6 @@ public class AdminUserEditActivity
);
}
- @Override
- public void onDeviceRegistrationDelete(DeviceNotificationToken.Id id) {
- environment.getApp().getRequests().send(
- requestParams -> notificationResource.deleteDeviceToken(requestParams, id.getUserId(), id.getDeviceId()),
- 204,
- () -> {
- adminContent.removeDeviceRegistration(id);
- environment.getEventBus().dispatch(new ShowSuccessEvent(
- environment.getMessages().registeredDeviceDeleted(id.getDeviceId())
- ));
- }
- );
- }
-
- @Override
- public void onDeviceRegistrationsRefresh() {
- loadDeviceRegistrations(() -> {});
- }
-
@Override
public void delete() {
adminContent.showConfirmation(
@@ -320,14 +297,14 @@ public class AdminUserEditActivity
user -> {
this.user = user;
this.realm = user.getRealm();
- loadRoles(() -> loadDeviceRegistrations(() -> {
+ loadRoles(() -> {
writeToView();
adminContent.setFormBusy(false);
adminContent.enableCreate(false);
adminContent.enableUpdate(true);
adminContent.enableDelete(true);
adminContent.enableResetPassword(true);
- }));
+ });
}
);
}
@@ -348,18 +325,6 @@ public class AdminUserEditActivity
);
}
- protected void loadDeviceRegistrations(Runnable onComplete) {
- environment.getApp().getRequests().sendAndReturn(
- deviceNotificationTokenMapper,
- requestParams -> notificationResource.getDeviceTokens(requestParams, userId),
- 200,
- deviceNotificationTokens -> {
- adminContent.setDeviceRegistrations(deviceNotificationTokens);
- onComplete.run();
- }
- );
- }
-
protected void writeToView() {
adminContent.setTenantName(realm);
adminContent.setUsername(user.getUsername());
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.java b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.java
index 16041ab60..363cc5aff 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.java
@@ -22,23 +22,19 @@ package org.openremote.app.client.admin.users.edit;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
-import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.*;
import com.google.inject.Provider;
-import org.openremote.app.client.widget.*;
-import org.openremote.app.client.widget.PushButton;
import org.openremote.app.client.Environment;
import org.openremote.app.client.admin.users.AdminUsersNavigation;
import org.openremote.app.client.app.dialog.Confirmation;
-import org.openremote.model.notification.DeviceNotificationToken;
-import org.openremote.model.Constants;
+import org.openremote.app.client.widget.*;
+import org.openremote.app.client.widget.PushButton;
import javax.inject.Inject;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
public class AdminUserEditImpl extends FormViewImpl implements AdminUserEdit {
@@ -318,28 +314,6 @@ public class AdminUserEditImpl extends FormViewImpl implements AdminUserEdit {
}
}
- @Override
- public void setDeviceRegistrations(List<DeviceNotificationToken> deviceNotificationTokens) {
- clearRegisteredDevices(deviceNotificationTokens.size() == 0);
- for (DeviceNotificationToken deviceNotificationToken : deviceNotificationTokens) {
- registeredDevicesContainer.add(new DeviceRegistrationItem(deviceNotificationToken));
- }
- }
-
- @Override
- public void removeDeviceRegistration(DeviceNotificationToken.Id id) {
- for (int i = 0; i < registeredDevicesContainer.getWidgetCount(); i++) {
- if (registeredDevicesContainer.getWidget(i) instanceof DeviceRegistrationItem) {
- DeviceRegistrationItem item = (DeviceRegistrationItem) registeredDevicesContainer.getWidget(i);
- if (item.getDeviceNotificationToken().getId().equals(id))
- registeredDevicesContainer.remove(i);
- }
- }
- if (registeredDevicesContainer.getWidgetCount() == 0) {
- clearRegisteredDevices(true);
- }
- }
-
@Override
public void enableCreate(boolean enable) {
createButton.setVisible(enable);
@@ -373,12 +347,6 @@ public class AdminUserEditImpl extends FormViewImpl implements AdminUserEdit {
presenter.delete();
}
- @UiHandler("refreshDeviceRegistrations")
- void refreshDeviceRegistrationsClicked(ClickEvent e) {
- if (presenter != null)
- presenter.onDeviceRegistrationsRefresh();
- }
-
protected void clearRegisteredDevices(boolean addEmptyMessage) {
registeredDevicesContainer.clear();
if (addEmptyMessage) {
@@ -387,82 +355,4 @@ public class AdminUserEditImpl extends FormViewImpl implements AdminUserEdit {
registeredDevicesContainer.add(emptyLabel);
}
}
-
- protected class DeviceRegistrationItem extends FlowPanel {
-
- private final DeviceNotificationToken deviceNotificationToken;
-
- public DeviceRegistrationItem(DeviceNotificationToken deviceNotificationToken) {
- this.deviceNotificationToken = deviceNotificationToken;
- setStyleName("flex-none layout vertical or-FormListItem");
-
- FormGroup deviceIdGroup = new FormGroup();
- deviceIdGroup.setFormGroupActions(new FormGroupActions());
- FormField deviceIdField = new FormField();
- FormLabel deviceIdLabel = new FormLabel(managerMessages.registeredDeviceId());
- deviceIdLabel.addStyleName("larger");
- deviceIdGroup.setFormLabel(deviceIdLabel);
- deviceIdGroup.setFormField(deviceIdField);
- FormInputText deviceIdTxt = new FormInputText(deviceNotificationToken.getId().getDeviceId());
- deviceIdTxt.setReadOnly(true);
- deviceIdField.add(deviceIdTxt);
- add(deviceIdGroup);
-
- FormButton deleteButton = new FormButton();
- deleteButton.setDanger(true);
- deleteButton.setIcon("trash-o");
- deleteButton.setText(managerMessages.deleteRegistration());
- deleteButton.addClickHandler(event -> {
- if (presenter != null)
- presenter.onDeviceRegistrationDelete(deviceNotificationToken.getId());
- });
- deviceIdGroup.getFormGroupActions().add(deleteButton);
-
- FlowPanel typeLoginPanel = new FlowPanel();
- typeLoginPanel.setStyleName("layout horizontal wrap");
- add(typeLoginPanel);
-
- FormGroup deviceTypeGroup = new FormGroup();
- FormField deviceTypeField = new FormField();
- FormLabel deviceTypeLabel = new FormLabel(managerMessages.registeredDeviceType());
- deviceTypeLabel.addStyleName("larger");
- deviceTypeGroup.setFormLabel(deviceTypeLabel);
- deviceTypeGroup.setFormField(deviceTypeField);
- FormOutputText deviceTypeOutput = new FormOutputText(
- deviceNotificationToken.getDeviceType() != null ? deviceNotificationToken.getDeviceType() : "-"
- );
- deviceTypeField.add(deviceTypeOutput);
- typeLoginPanel.add(deviceTypeGroup);
-
- // TODO The label says "first login" because we still don't capture last login on service/from consoles
- FormGroup lastLoginGroup = new FormGroup();
- FormField lastLoginField = new FormField();
- FormLabel lastLoginLabel = new FormLabel(managerMessages.registeredDeviceLastLogin());
- lastLoginLabel.addStyleName("larger");
- lastLoginGroup.setFormLabel(lastLoginLabel);
- lastLoginGroup.setFormField(lastLoginField);
- FormOutputText lastLoginOutput = new FormOutputText(
- DateTimeFormat.getFormat(Constants.DEFAULT_DATETIME_FORMAT).format(deviceNotificationToken.getUpdatedOn())
- );
- lastLoginField.add(lastLoginOutput);
- typeLoginPanel.add(lastLoginGroup);
-
- FormGroup notificationTokenGroup = new FormGroup();
- notificationTokenGroup.setFormGroupActions(new FormGroupActions());
- FormField notificationTokenField = new FormField();
- FormLabel notificationTokenLabel = new FormLabel(managerMessages.registeredDeviceNotificationToken());
- notificationTokenLabel.addStyleName("larger");
- notificationTokenGroup.setFormLabel(notificationTokenLabel);
- notificationTokenGroup.setFormField(notificationTokenField);
- FormInputText notificationTokenTxt = new FormInputText(deviceNotificationToken.getToken());
- notificationTokenTxt.setReadOnly(true);
- notificationTokenTxt.addStyleName("flex");
- notificationTokenField.add(notificationTokenTxt);
- add(notificationTokenGroup);
- }
-
- public DeviceNotificationToken getDeviceNotificationToken() {
- return deviceNotificationToken;
- }
- }
}
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.ui.xml b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.ui.xml
index fcb658f83..53aa8de7b 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.ui.xml
+++ b/client/src/main/java/org/openremote/app/client/admin/users/edit/AdminUserEditImpl.ui.xml
@@ -124,9 +124,6 @@
</g:HTMLPanel>
- <g:FlowPanel ui:field="registeredDevicesContainer"
- styleName="flex layout vertical {widgetStyle.MainContent} {widgetStyle.FormList}"/>
-
<g:FlowPanel styleName="flex-none layout vertical {widgetStyle.MainContent}">
<w:FormGroup>
<w:field>
@@ -137,9 +134,6 @@
visible="false" icon="save"/>
<w:FormButton ui:field="deleteButton" danger="true" text="{managerMessages.deleteUser}"
visible="false" icon="trash"/>
- <w:FormButton ui:field="refreshDeviceRegistrations"
- text="{managerMessages.refreshDeviceRegistrations}"
- icon="refresh"/>
</w:FormField>
</w:field>
</w:FormGroup>
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditor.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditor.java
index d58ae816a..b265c23f0 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditor.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditor.java
@@ -20,15 +20,15 @@
package org.openremote.app.client.admin.users.notifications;
import org.openremote.model.interop.Consumer;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
public interface AdminUserNotificationEditor {
void reset();
- void setAlertNotification(AlertNotification notification);
+ void setNotification(Notification notification);
- void setOnSend(Consumer<AlertNotification> onSend);
+ void setOnSend(Consumer<Notification> onSend);
void setOnClose(Runnable onClose);
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditorImpl.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditorImpl.java
index 9f5efa729..25b719878 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditorImpl.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationEditorImpl.java
@@ -26,7 +26,9 @@ import org.openremote.app.client.widget.*;
import org.openremote.app.client.app.dialog.Dialog;
import org.openremote.app.client.i18n.ManagerMessages;
import org.openremote.model.interop.Consumer;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.notification.SentNotification;
import javax.inject.Inject;
@@ -43,9 +45,9 @@ public class AdminUserNotificationEditorImpl implements AdminUserNotificationEdi
final protected FormTextArea notificationMessageInput = new FormTextArea();
final protected FormInputText notificationAppUrlInput = new FormInputText();
- AlertNotification alertNotification;
+ Notification alertNotification;
- Consumer<AlertNotification> onSend;
+ Consumer<Notification> onSend;
Runnable onClose;
@Inject
@@ -70,7 +72,7 @@ public class AdminUserNotificationEditorImpl implements AdminUserNotificationEdi
sendButton.addStyleName(widgetStyle.PushButton());
sendButton.addStyleName(widgetStyle.FormButtonPrimary());
sendButton.addClickHandler(event -> {
- AlertNotification notification = buildAlertNotification();
+ Notification notification = buildNotification();
if (notification != null) {
if (onSend != null)
onSend.accept(notification);
@@ -139,16 +141,16 @@ public class AdminUserNotificationEditorImpl implements AdminUserNotificationEdi
}
@Override
- public void setAlertNotification(AlertNotification notification) {
+ public void setNotification(Notification notification) {
this.alertNotification = notification;
errorPanel.clear();
errorPanel.setVisible(false);
- notificationTitleInput.setText(notification.getTitle());
- notificationMessageInput.setText(notification.getMessage());
- notificationAppUrlInput.setText(notification.getAppUrl());
+// notificationTitleInput.setText(notification.getTitle());
+// notificationMessageInput.setText(notification.getBody());
+// notificationAppUrlInput.setText(notification.getAppUrl());
}
- public void setOnSend(Consumer<AlertNotification> onSend) {
+ public void setOnSend(Consumer<Notification> onSend) {
this.onSend = onSend;
}
@@ -160,7 +162,7 @@ public class AdminUserNotificationEditorImpl implements AdminUserNotificationEdi
dialog.open();
}
- protected AlertNotification buildAlertNotification() {
+ protected Notification buildNotification() {
errorPanel.clear();
String notificationTitle = notificationTitleInput.getText();
String notificationMessage = notificationMessageInput.getText();
@@ -175,9 +177,10 @@ public class AdminUserNotificationEditorImpl implements AdminUserNotificationEdi
return null;
}
errorPanel.setVisible(false);
- alertNotification.setTitle(notificationTitle);
- alertNotification.setMessage(notificationMessage);
- alertNotification.setAppUrl(notificationAppUrl);
- return alertNotification;
+// alertNotification.setTitle(notificationTitle);
+// alertNotification.setBody(notificationMessage);
+// alertNotification.setAppUrl(notificationAppUrl);
+// return alertNotification;
+ return null;
}
}
\ No newline at end of file
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotifications.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotifications.java
index 139a6193e..e58fbaccc 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotifications.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotifications.java
@@ -21,7 +21,8 @@ package org.openremote.app.client.admin.users.notifications;
import org.openremote.app.client.admin.AdminContent;
import org.openremote.app.client.admin.users.AbstractAdminUsersPlace;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.notification.SentNotification;
public interface AdminUserNotifications extends AdminContent {
@@ -43,7 +44,7 @@ public interface AdminUserNotifications extends AdminContent {
void setUsername(String username);
- void setNotifications(AlertNotification[] notifications);
+ void setNotifications(SentNotification[] notifications);
void removeNotification(Long id);
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
index d1ce70608..46246f0a7 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsActivity.java
@@ -28,15 +28,14 @@ import org.openremote.app.client.mvp.AcceptsView;
import org.openremote.app.client.mvp.AppActivity;
import org.openremote.model.event.bus.EventBus;
import org.openremote.model.event.bus.EventRegistration;
-import org.openremote.model.notification.ActionType;
-import org.openremote.model.notification.AlertAction;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationResource;
import org.openremote.model.security.User;
import org.openremote.model.security.UserResource;
import javax.inject.Inject;
import java.util.Collection;
+import java.util.Collections;
public class AdminUserNotificationsActivity
extends AbstractAdminActivity<AdminUserNotificationsPlace, AdminUserNotifications>
@@ -49,14 +48,14 @@ public class AdminUserNotificationsActivity
final protected RoleArrayMapper roleArrayMapper;
final protected AdminUserNotificationEditor notificationEditor;
final protected NotificationResource notificationResource;
- final protected AlertNotificationMapper alertNotificationMapper;
- final protected AlertNotificationArrayMapper alertNotificationArrayMapper;
+ final protected NotificationMapper notificationMapper;
+ final protected SentNotificationArrayMapper alertNotificationArrayMapper;
protected AdminUserEditPlace place;
protected String realm;
protected String userId;
protected User user;
- protected AlertNotification alertNotification;
+ protected Notification alertNotification;
@Inject
public AdminUserNotificationsActivity(Environment environment,
@@ -69,8 +68,8 @@ public class AdminUserNotificationsActivity
RoleArrayMapper roleArrayMapper,
AdminUserNotificationEditor notificationEditor,
NotificationResource notificationResource,
- AlertNotificationMapper alertNotificationMapper,
- AlertNotificationArrayMapper alertNotificationArrayMapper) {
+ NotificationMapper notificationMapper,
+ SentNotificationArrayMapper alertNotificationArrayMapper) {
super(adminView, adminNavigationPresenter, view);
this.environment = environment;
this.userResource = userResource;
@@ -79,7 +78,7 @@ public class AdminUserNotificationsActivity
this.roleArrayMapper = roleArrayMapper;
this.notificationEditor = notificationEditor;
this.notificationResource = notificationResource;
- this.alertNotificationMapper = alertNotificationMapper;
+ this.notificationMapper = notificationMapper;
this.alertNotificationArrayMapper = alertNotificationArrayMapper;
}
@@ -122,14 +121,13 @@ public class AdminUserNotificationsActivity
if (this.alertNotification == null)
this.alertNotification = createDefaultNotification();
- // TODO Constraint violation handler and @Valid AlertNotification on resource method?
- notificationEditor.setAlertNotification(this.alertNotification);
+ notificationEditor.setNotification(this.alertNotification);
notificationEditor.setOnSend(updatedNotification -> {
adminContent.setFormBusy(true);
this.alertNotification = updatedNotification;
environment.getApp().getRequests().sendWith(
- alertNotificationMapper,
- requestParams -> notificationResource.storeNotificationForUser(requestParams, userId, this.alertNotification),
+ notificationMapper,
+ requestParams -> notificationResource.sendNotification(requestParams, this.alertNotification),
204,
() -> {
environment.getEventBus().dispatch(new ShowSuccessEvent(
@@ -152,7 +150,12 @@ public class AdminUserNotificationsActivity
public void onNotificationsDelete() {
adminContent.setFormBusy(true);
environment.getApp().getRequests().send(
- requestParams -> notificationResource.removeNotificationsOfUser(requestParams, userId),
+ requestParams -> notificationResource.removeNotifications(requestParams,
+ null,
+ null,
+ null,
+ Collections.singletonList(userId),
+ null),
204,
() -> {
environment.getEventBus().dispatch(new ShowSuccessEvent(
@@ -167,7 +170,7 @@ public class AdminUserNotificationsActivity
public void onNotificationDelete(Long id) {
adminContent.setFormBusy(true);
environment.getApp().getRequests().send(
- requestParams -> notificationResource.removeNotification(requestParams, userId, id),
+ requestParams -> notificationResource.removeNotification(requestParams, id),
204,
() -> {
adminContent.setFormBusy(false);
@@ -179,19 +182,16 @@ public class AdminUserNotificationsActivity
);
}
- protected AlertNotification createDefaultNotification() {
- AlertNotification alertNotification = new AlertNotification(
- "Hello User",
- "This is a test message.",
- // TODO: Remove below once consoles updated to use action appUrl
- "/#"
- );
- AlertAction alertAction = new AlertAction();
- alertAction.setTitle(environment.getMessages().notificationOpenApplicationDetails());
- alertAction.setActionType(ActionType.LINK);
- alertAction.setAppUrl("/#");
- alertNotification.addAction(alertAction);
- return alertNotification;
+ protected Notification createDefaultNotification() {
+ Notification notification = new Notification(null, null, null);
+ return notification;
+//
+// PushNotificationAction alertAction = new PushNotificationAction();
+// alertAction.setTitle(environment.getMessages().notificationOpenApplicationDetails());
+// alertAction.setActionType(ActionType.LINK);
+// alertAction.setAppUrl("/#");
+// notification.addAction(alertAction);
+// return notification;
}
protected void loadUser() {
@@ -204,9 +204,7 @@ public class AdminUserNotificationsActivity
this.user = user;
this.realm = user.getRealm();
adminContent.setUsername(user.getFullName());
- loadNotifications(() -> {
- adminContent.setFormBusy(false);
- });
+ loadNotifications(() -> adminContent.setFormBusy(false));
}
);
}
@@ -214,7 +212,12 @@ public class AdminUserNotificationsActivity
protected void loadNotifications(Runnable onComplete) {
environment.getApp().getRequests().sendAndReturn(
alertNotificationArrayMapper,
- requestParams -> notificationResource.getNotificationsOfUser(requestParams, userId),
+ requestParams -> notificationResource.getNotifications(requestParams,
+ null,
+ null,
+ null,
+ Collections.singletonList(userId),
+ null),
200,
notifications -> {
adminContent.setNotifications(notifications);
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsImpl.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsImpl.java
index 618470d20..03f2dfa7a 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsImpl.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/AdminUserNotificationsImpl.java
@@ -32,7 +32,9 @@ import org.openremote.app.client.Environment;
import org.openremote.app.client.admin.users.AdminUsersNavigation;
import org.openremote.app.client.app.dialog.Confirmation;
import org.openremote.model.Constants;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.notification.SentNotification;
import javax.inject.Inject;
@@ -111,9 +113,9 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
}
@Override
- public void setNotifications(AlertNotification[] notifications) {
+ public void setNotifications(SentNotification[] notifications) {
clearNotifications(notifications.length == 0);
- for (AlertNotification notification : notifications) {
+ for (SentNotification notification : notifications) {
notificationsContainer.add(new NotificationItem(notification));
}
}
@@ -145,9 +147,9 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
protected class NotificationItem extends FlowPanel {
- private final AlertNotification notification;
+ private final SentNotification notification;
- public NotificationItem(AlertNotification notification) {
+ public NotificationItem(SentNotification notification) {
this.notification = notification;
setStyleName("flex-none layout vertical or-FormListItem");
@@ -157,7 +159,7 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
FormLabel statusLabel = new FormLabel(managerMessages.deliveryStatus());
statusGroup.setFormLabel(statusLabel);
statusGroup.setFormField(statusField);
- FormOutputText statusTxt = new FormOutputText(notification.getDeliveryStatus().toString());
+ FormOutputText statusTxt = new FormOutputText("");
statusField.add(statusTxt);
FormGroup createdOnGroup = new FormGroup();
@@ -168,7 +170,7 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
createdOnGroup.setFormLabel(createdOnLabel);
createdOnGroup.setFormField(createdOnField);
FormOutputText createdOnTxt = new FormOutputText(
- DateTimeFormat.getFormat(Constants.DEFAULT_DATETIME_FORMAT).format(notification.getCreatedOn())
+ DateTimeFormat.getFormat(Constants.DEFAULT_DATETIME_FORMAT).format(notification.getSentOn())
);
createdOnTxt.addStyleName("flex");
createdOnField.add(createdOnTxt);
@@ -194,7 +196,7 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
FormLabel titleLabel = new FormLabel(managerMessages.title());
titleGroup.setFormLabel(titleLabel);
titleGroup.setFormField(titleField);
- FormOutputText titleTxt = new FormOutputText(notification.getTitle());
+ FormOutputText titleTxt = new FormOutputText(/*notification.getTitle()*/);
titleField.add(titleTxt);
add(titleGroup);
@@ -208,11 +210,11 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
messageTxt.setHeight("3em");
messageTxt.setResizable(false);
messageTxt.setBorder(true);
- messageTxt.setText(notification.getMessage());
+ messageTxt.setText(""/*notification.getBody()*/);
messageField.add(messageTxt);
add(messageGroup);
- for (int i = 0; i < notification.getActions().length(); i++) {
+/* for (int i = 0; i < notification.getActions().length(); i++) {
notification.getActions().get(i).ifPresent(action -> {
FormGroup actionGroup = new FormGroup();
FormField actionField = new FormField();
@@ -228,19 +230,19 @@ public class AdminUserNotificationsImpl extends FormViewImpl implements AdminUse
actionField.add(actionTxt);
add(actionGroup);
});
- }
+ }*/
FormGroup appUrlGroup = new FormGroup();
FormField appUrlField = new FormField();
FormLabel appUrlLabel = new FormLabel(managerMessages.notificationAppUrl());
appUrlGroup.setFormLabel(appUrlLabel);
appUrlGroup.setFormField(appUrlField);
- FormOutputText appUrlTxt = new FormOutputText(notification.getAppUrl());
+ FormOutputText appUrlTxt = new FormOutputText(/*notification.getAppUrl()*/);
appUrlField.add(appUrlTxt);
add(appUrlGroup);
}
- public AlertNotification getNotification() {
+ public SentNotification getNotification() {
return notification;
}
}
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationMapper.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/NotificationMapper.java
similarity index 77%
rename from client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationMapper.java
rename to client/src/main/java/org/openremote/app/client/admin/users/notifications/NotificationMapper.java
index cd7d8a6f7..7aff13cdd 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationMapper.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/NotificationMapper.java
@@ -23,10 +23,11 @@ import com.github.nmorel.gwtjackson.client.ObjectMapper;
import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
import org.openremote.app.client.interop.jackson.DefaultJsonMixin;
import org.openremote.app.client.rest.EntityWriter;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.PushNotificationMessage;
-@JsonMixIns({@JsonMixIns.JsonMixIn(target = AlertNotification.class, mixIn = DefaultJsonMixin.class)})
-public interface AlertNotificationMapper
- extends ObjectMapper<AlertNotification>,
- EntityWriter<AlertNotification> {
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = Notification.class, mixIn = DefaultJsonMixin.class)})
+public interface NotificationMapper
+ extends ObjectMapper<Notification>,
+ EntityWriter<Notification> {
}
diff --git a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationArrayMapper.java b/client/src/main/java/org/openremote/app/client/admin/users/notifications/SentNotificationArrayMapper.java
similarity index 73%
rename from client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationArrayMapper.java
rename to client/src/main/java/org/openremote/app/client/admin/users/notifications/SentNotificationArrayMapper.java
index a0e6f638d..01433259d 100644
--- a/client/src/main/java/org/openremote/app/client/admin/users/notifications/AlertNotificationArrayMapper.java
+++ b/client/src/main/java/org/openremote/app/client/admin/users/notifications/SentNotificationArrayMapper.java
@@ -23,10 +23,12 @@ import com.github.nmorel.gwtjackson.client.ObjectMapper;
import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
import org.openremote.app.client.interop.jackson.DefaultJsonMixin;
import org.openremote.app.client.rest.EntityReader;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.notification.SentNotification;
-@JsonMixIns({@JsonMixIns.JsonMixIn(target = AlertNotification.class, mixIn = DefaultJsonMixin.class)})
-public interface AlertNotificationArrayMapper
- extends ObjectMapper<AlertNotification[]>,
- EntityReader<AlertNotification[]> {
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = SentNotification.class, mixIn = DefaultJsonMixin.class)})
+public interface SentNotificationArrayMapper
+ extends ObjectMapper<SentNotification[]>,
+ EntityReader<SentNotification[]> {
}
diff --git a/client/src/main/java/org/openremote/app/client/assets/AssetQueryMapper.java b/client/src/main/java/org/openremote/app/client/assets/AssetQueryMapper.java
index 9380b3b6e..e07c47f74 100644
--- a/client/src/main/java/org/openremote/app/client/assets/AssetQueryMapper.java
+++ b/client/src/main/java/org/openremote/app/client/assets/AssetQueryMapper.java
@@ -24,7 +24,7 @@ import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
import org.openremote.app.client.interop.jackson.DefaultJsonMixin;
import org.openremote.app.client.rest.EntityReader;
import org.openremote.app.client.rest.EntityWriter;
-import org.openremote.model.asset.AssetQuery;
+import org.openremote.model.query.AssetQuery;
@JsonMixIns({@JsonMixIns.JsonMixIn(target = AssetQuery.class, mixIn = DefaultJsonMixin.class)})
public interface AssetQueryMapper
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
index 8971776dd..cb67f35e4 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
@@ -48,6 +48,10 @@ import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.http.ConstraintViolation;
import org.openremote.model.interop.Consumer;
import org.openremote.model.map.MapResource;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.filter.AttributeMetaPredicate;
+import org.openremote.model.query.filter.BooleanPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.util.EnumUtil;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
@@ -59,7 +63,6 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
-import static org.openremote.model.asset.AssetQuery.*;
import static org.openremote.model.attribute.Attribute.ATTRIBUTE_NAME_VALIDATOR;
import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
@@ -375,7 +378,7 @@ public class AssetEditActivity
// Limit to assets that have the same realm as the asset being edited (if it has been assigned a realm
// otherwise the query will be automatically restricted to the logged in users realm)
if (!isNullOrEmpty(asset.getRealmId())) {
- query.tenant(new AssetQuery.TenantPredicate(asset.getRealmId()));
+ query.tenant(new TenantPredicate(asset.getRealmId()));
}
}
diff --git a/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java b/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
index 1dc26e7b5..5903b1d22 100644
--- a/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
+++ b/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
@@ -26,11 +26,13 @@ import org.openremote.app.client.assets.AssetArrayMapper;
import org.openremote.app.client.assets.AssetMapper;
import org.openremote.app.client.assets.AssetQueryMapper;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.asset.AssetResource;
import org.openremote.model.asset.AssetTreeModifiedEvent;
import org.openremote.model.event.shared.TenantFilter;
import org.openremote.model.interop.Consumer;
+import org.openremote.model.query.filter.ParentPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
import org.openremote.model.security.TenantResource;
@@ -247,8 +249,8 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {
assetResource.queryAssets(
requestParams,
new AssetQuery()
- .tenant(new AssetQuery.TenantPredicate(parent.getId()))
- .parent(new AssetQuery.ParentPredicate(true))
+ .tenant(new TenantPredicate(parent.getId()))
+ .parent(new ParentPredicate(true))
);
} else if (parent instanceof RootTreeNode) {
assetResource.getCurrentUserAssets(requestParams);
diff --git a/container/src/main/java/org/openremote/container/security/AuthContext.java b/container/src/main/java/org/openremote/container/security/AuthContext.java
index f861f5663..42d31d4b9 100644
--- a/container/src/main/java/org/openremote/container/security/AuthContext.java
+++ b/container/src/main/java/org/openremote/container/security/AuthContext.java
@@ -36,7 +36,7 @@ public interface AuthContext {
* @return <code>true</code> if the user is authenticated in the "master" realm and has the realm role "admin".
*/
default boolean isSuperUser() {
- return getAuthenticatedRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
+ return Constants.MASTER_REALM.equals(getAuthenticatedRealm()) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
}
boolean hasRealmRole(String role);
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index bfd474323..37c812eef 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -41,6 +41,8 @@ import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeEvent.Source;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.event.shared.TenantFilter;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.filter.AttributeRefPredicate;
import org.openremote.model.security.ClientRole;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
@@ -463,7 +465,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
new AssetQuery()
.select(new AssetQuery.Select(AssetQuery.Include.ALL))
.attributeMeta(
- new AssetQuery.AttributeRefPredicate(
+ new AttributeRefPredicate(
AssetMeta.AGENT_LINK,
protocolAttributeRef.getEntityId(),
protocolAttributeRef.getAttributeName()
@@ -493,7 +495,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
new AssetQuery()
.select(new AssetQuery.Select(AssetQuery.Include.ALL))
.attributeMeta(
- new AssetQuery.AttributeRefPredicate(
+ new AttributeRefPredicate(
AssetMeta.AGENT_LINK,
protocolAttributeRef.getEntityId(),
protocolAttributeRef.getAttributeName()
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
index 0a96fd4c8..c2150d7fe 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
@@ -25,7 +25,7 @@ import org.openremote.manager.asset.AssetProcessingException.Reason;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.asset.AssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.attribute.*;
import org.openremote.model.attribute.AttributeEvent.Source;
import org.openremote.model.util.Pair;
@@ -37,8 +37,8 @@ import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.logging.Logger;
-import static org.openremote.model.asset.AssetQuery.Include;
-import static org.openremote.model.asset.AssetQuery.Select;
+import static org.openremote.model.query.AssetQuery.Include;
+import static org.openremote.model.query.AssetQuery.Select;
import static org.openremote.model.attribute.AttributeEvent.Source.ATTRIBUTE_LINKING_SERVICE;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 1b3e899e8..e6d42083f 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -46,7 +46,6 @@ import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
import javax.persistence.EntityManager;
-import javax.ws.rs.WebApplicationException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -54,8 +53,6 @@ import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static javax.ws.rs.core.Response.Status.FORBIDDEN;
-import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.manager.asset.AssetProcessingException.Reason.*;
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index 8b732f50e..a627c92c2 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -25,9 +25,12 @@ import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.Constants;
import org.openremote.model.asset.*;
-import org.openremote.model.asset.BaseAssetQuery.Select;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery.Select;
import org.openremote.model.attribute.*;
import org.openremote.model.http.RequestParams;
+import org.openremote.model.query.filter.ParentPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.Value;
@@ -42,7 +45,7 @@ import java.util.logging.Logger;
import static javax.ws.rs.core.Response.Status.*;
import static org.openremote.container.Container.JSON;
-import static org.openremote.model.asset.AssetQuery.*;
+import static org.openremote.model.query.AssetQuery.*;
import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
@@ -371,7 +374,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// Process asynchronously but block for a little while waiting for the result
Map<String, Object> headers = new HashMap<>();
headers.put(AttributeEvent.HEADER_SOURCE, CLIENT);
- //TODO needed for anonymous?
+
if (isAuthenticated()) {
headers.put(Constants.AUTH_CONTEXT, getAuthContext());
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 391445a74..b4a6aa6f5 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -41,7 +41,6 @@ import org.openremote.container.web.WebService;
import org.openremote.manager.asset.console.ConsoleResourceImpl;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.security.ManagerIdentityService;
-import org.openremote.manager.security.UserConfiguration;
import org.openremote.model.Constants;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
@@ -50,6 +49,9 @@ import org.openremote.model.attribute.AttributeType;
import org.openremote.model.calendar.CalendarEvent;
import org.openremote.model.calendar.RecurrenceRule;
import org.openremote.model.event.shared.TenantFilter;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.filter.*;
import org.openremote.model.security.ClientRole;
import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
@@ -60,6 +62,7 @@ import org.postgresql.util.PGobject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
+import javax.persistence.TypedQuery;
import java.sql.*;
import java.util.*;
import java.util.Date;
@@ -72,11 +75,11 @@ import static org.openremote.container.persistence.PersistenceEvent.isPersistenc
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
import static org.openremote.manager.event.ClientEventService.getSessionKey;
import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
-import static org.openremote.model.asset.BaseAssetQuery.*;
-import static org.openremote.model.asset.BaseAssetQuery.Access.PRIVATE_READ;
-import static org.openremote.model.asset.BaseAssetQuery.Access.RESTRICTED_READ;
-import static org.openremote.model.asset.BaseAssetQuery.Include.ALL;
-import static org.openremote.model.asset.BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
+import static org.openremote.model.query.BaseAssetQuery.*;
+import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ;
+import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ;
+import static org.openremote.model.query.BaseAssetQuery.Include.ALL;
+import static org.openremote.model.query.BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetStorageService extends RouteBuilder implements ContainerService {
@@ -395,7 +398,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
Asset asset = em.find(Asset.class, assetId);
if (asset != null) {
List<Asset> children = findAll(em, new AssetQuery()
- .parent(new AssetQuery.ParentPredicate(asset.getId()))
+ .parent(new ParentPredicate(asset.getId()))
);
if (children.size() > 0)
return false;
@@ -406,53 +409,118 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
});
}
+ public boolean isUserAsset(String assetId) {
+ return isUserAsset(null, assetId);
+ }
+
public boolean isUserAsset(String userId, String assetId) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+ try {
+ String queryStr = TextUtil.isNullOrEmpty(userId) ?
+ "select count(ua) from UserAsset ua where ua.id.assetId = :assetId" :
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId";
+
+ TypedQuery<Long> query = entityManager.createQuery(
+ queryStr,
+ Long.class).setParameter("assetId", assetId);
+
+ if (!TextUtil.isNullOrEmpty(userId)) {
+ query.setParameter("userId", userId);
+ }
+
+ return query.getSingleResult() > 0;
+ } catch (NoResultException ex) {
+ return false;
+ }
+ });
+ }
+
+ public boolean isUserAssets(String userId, List<String> assetIds) {
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId",
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId in :assetIds",
Long.class)
.setParameter("userId", userId)
- .setParameter("assetId", assetId)
- .getSingleResult() > 0;
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
} catch (NoResultException ex) {
return false;
}
});
}
- public List<UserAsset> findUserAssets(String realmId, String userId, String assetId) {
+ /**
+ * Indicates if the specified asset belongs to the specified realm
+ */
+ public boolean isRealmAsset(String realmId, String assetId) {
+ return isRealmAssets(realmId, Collections.singletonList(assetId));
+ }
+
+ /**
+ * Indicates if the specified assets belong to the specified realm
+ */
+ public boolean isRealmAssets(String realmId, List<String> assetIds) {
return persistenceService.doReturningTransaction(entityManager -> {
- if (isNullOrEmpty(userId) && isNullOrEmpty(assetId)) {
- return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId order by ua.createdOn desc",
- UserAsset.class
- ).setParameter("realmId", realmId).getResultList();
- } else if (isNullOrEmpty(assetId)) {
+ try {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId order by ua.createdOn desc",
- UserAsset.class
- ).setParameter("realmId", realmId).setParameter("userId",
- userId).getResultList();
+ "select count(a) from Asset a where a.realmId = :realmId and a.id in :assetIds",
+ Long.class)
+ .setParameter("realmId", realmId)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
+ } catch (NoResultException ex) {
+ return false;
+ }
+ });
+ }
- } else if (isNullOrEmpty(userId)) {
- return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.assetId = :assetId order by ua.createdOn desc",
- UserAsset.class
- ).setParameter("realmId", realmId).setParameter("assetId",
- assetId).getResultList();
- } else {
+ public boolean isDescendantAsset(String parentAssetId, String assetId) {
+ return isDescendantAssets(parentAssetId, Collections.singletonList(assetId));
+ }
+
+ public boolean isDescendantAssets(String parentAssetId, List<String> assetIds) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+ try {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId and ua.id.assetId = :assetId order by ua.createdOn desc",
- UserAsset.class
- ).setParameter("realmId", realmId).setParameter("userId",
- userId).setParameter(
- "assetId",
- assetId).getResultList();
+ "select count(a) from Asset a where :parentAssetId = any(get_asset_tree_path(a.ID)) AND a.id IN :assetIds",
+ Long.class)
+ .setParameter("parentAssetId", parentAssetId)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
+ } catch (NoResultException ex) {
+ return false;
}
});
}
+ public List<UserAsset> findUserAssets(String realmId, String userId, String assetId) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+ StringBuilder sb = new StringBuilder();
+ Map<String, Object> parameters = new HashMap<>(3);
+ sb.append("select ua from UserAsset ua where 1=1");
+
+ if (!isNullOrEmpty(realmId)) {
+ sb.append(" and ua.id.realmId = :realmId");
+ parameters.put("realmId", realmId);
+ }
+ if (!isNullOrEmpty(userId)) {
+ sb.append(" and ua.id.userId = :userId");
+ parameters.put("userId", userId);
+ }
+ if (!isNullOrEmpty(assetId)) {
+ sb.append(" and ua.id.assetId = :assetId");
+ parameters.put("assetId", assetId);
+ }
+
+ sb.append(" order by ua.createdOn desc");
+
+ TypedQuery<UserAsset> query = entityManager.createQuery(sb.toString(), UserAsset.class);
+ parameters.forEach(query::setParameter);
+ return query.getResultList();
+ });
+ }
+
/**
* This used to automatically make the user restricted as well but this has been disabled as it no longer fitted
* with use cases.
@@ -516,7 +584,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
query.select.access = PRIVATE_READ;
// Default to order by creation date if the query may return multiple results
- if (query.orderBy == null && query.id == null)
+ if (query.orderBy == null && query.ids == null)
query.orderBy = new OrderBy(OrderBy.Property.CREATED_ON);
PreparedAssetQuery querySql = buildQuery(query);
@@ -675,10 +743,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (access != PRIVATE_READ) {
// Filter non-private access attributes
- AssetQuery.AttributeMetaPredicate accessPredicate =
- new AssetQuery.AttributeMetaPredicate()
+ AttributeMetaPredicate accessPredicate =
+ new AttributeMetaPredicate()
.itemName(access == RESTRICTED_READ ? AssetMeta.ACCESS_RESTRICTED_READ : AssetMeta.ACCESS_PUBLIC_READ)
- .itemValue(new AssetQuery.BooleanPredicate(true));
+ .itemValue(new BooleanPredicate(true));
sb.append(buildAttributeMetaFilter(accessPredicate, binders));
}
@@ -711,7 +779,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append("join PUBLIC.REALM_ATTRIBUTE RA on RA.REALM_ID = R.ID and RA.NAME = 'displayName' ");
}
- if ((!recursive || level == 3) && query.id == null && query.userId != null) {
+ if ((!recursive || level == 3) && query.ids == null && query.userId != null) {
sb.append("cross join USER_ASSET ua ");
}
@@ -729,7 +797,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected String buildOrderByString(BaseAssetQuery query) {
StringBuilder sb = new StringBuilder();
- if (query.id != null && !query.select.recursive) {
+ if (query.ids != null && !query.select.recursive) {
return sb.toString();
}
@@ -771,10 +839,18 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return sb.toString();
}
- if (level == 1 && query.id != null) {
- sb.append(" and A.ID = ?");
+ if (level == 1 && query.ids != null && !query.ids.isEmpty()) {
+ sb.append(" and A.ID IN (?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.id));
+ binders.add(st -> st.setString(pos, (String)query.ids.get(0)));
+
+ for (int i=1; i<query.ids.size(); i++) {
+ sb.append(",?");
+ final int pos2 = binders.size() + 1;
+ final int index = i;
+ binders.add(st -> st.setString(pos2, (String)query.ids.get(index)));
+ }
+ sb.append(")");
}
if (level == 1 && query.name != null) {
@@ -906,7 +982,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
if (query.attribute != null) {
- for (AssetQuery.AttributePredicate attributePredicate : query.attribute) {
+ for (AttributePredicate attributePredicate : query.attribute) {
StringBuilder attributeFilterBuilder = new StringBuilder();
attributeFilterBuilder.append(buildAttributeFilter(attributePredicate, binders));
@@ -923,7 +999,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return sb.toString();
}
- protected String buildAttributeMetaFilter(AssetQuery.AttributeMetaPredicate attributeMetaPredicate, List<ParameterBinder> binders) {
+ protected String buildAttributeMetaFilter(AttributeMetaPredicate attributeMetaPredicate, List<ParameterBinder> binders) {
StringBuilder attributeMetaBuilder = new StringBuilder();
if (attributeMetaPredicate.itemNamePredicate != null) {
@@ -948,8 +1024,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, attributeMetaPredicate.itemNamePredicate.prepareValue()));
}
if (attributeMetaPredicate.itemValuePredicate != null) {
- if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringPredicate) {
- AssetQuery.StringPredicate stringPredicate = (AssetQuery.StringPredicate) attributeMetaPredicate.itemValuePredicate;
+ if (attributeMetaPredicate.itemValuePredicate instanceof StringPredicate) {
+ StringPredicate stringPredicate = (StringPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(stringPredicate.caseSensitive
? " and AM.VALUE #>> '{value}'"
: " and upper(AM.VALUE #>> '{value}')"
@@ -969,15 +1045,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
- } else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.BooleanPredicate) {
- AssetQuery.BooleanPredicate booleanPredicate = (AssetQuery.BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
+ } else if (attributeMetaPredicate.itemValuePredicate instanceof BooleanPredicate) {
+ BooleanPredicate booleanPredicate = (BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(")
.append(booleanPredicate.value)
.append(")");
- } else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringArrayPredicate) {
- AssetQuery.StringArrayPredicate stringArrayPredicate = (AssetQuery.StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
+ } else if (attributeMetaPredicate.itemValuePredicate instanceof StringArrayPredicate) {
+ StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
- AssetQuery.StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
+ StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeMetaBuilder.append(stringPredicate.caseSensitive
? " and AM.VALUE #> '{value}' ->> " + i
: " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
@@ -1004,7 +1080,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return attributeMetaBuilder.toString();
}
- protected String buildAttributeFilter(AssetQuery.AttributePredicate attributePredicate, List<ParameterBinder> binders) {
+ protected String buildAttributeFilter(AttributePredicate attributePredicate, List<ParameterBinder> binders) {
StringBuilder attributeBuilder = new StringBuilder();
if (attributePredicate.name != null) {
@@ -1031,8 +1107,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, attributePredicate.name.prepareValue()));
}
if (attributePredicate.value != null) {
- if (attributePredicate.value instanceof AssetQuery.StringPredicate) {
- AssetQuery.StringPredicate stringPredicate = (AssetQuery.StringPredicate) attributePredicate.value;
+ if (attributePredicate.value instanceof StringPredicate) {
+ StringPredicate stringPredicate = (StringPredicate) attributePredicate.value;
attributeBuilder.append(stringPredicate.caseSensitive
? " and AX.VALUE #>> '{value}'"
: " and upper(AX.VALUE #>> '{value}')"
@@ -1052,15 +1128,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
- } else if (attributePredicate.value instanceof AssetQuery.BooleanPredicate) {
- AssetQuery.BooleanPredicate booleanPredicate = (AssetQuery.BooleanPredicate) attributePredicate.value;
+ } else if (attributePredicate.value instanceof BooleanPredicate) {
+ BooleanPredicate booleanPredicate = (BooleanPredicate) attributePredicate.value;
attributeBuilder.append(" and AX.VALUE #> '{value}' = to_jsonb(")
.append(booleanPredicate.value)
.append(")");
- } else if (attributePredicate.value instanceof AssetQuery.StringArrayPredicate) {
- AssetQuery.StringArrayPredicate stringArrayPredicate = (AssetQuery.StringArrayPredicate) attributePredicate.value;
+ } else if (attributePredicate.value instanceof StringArrayPredicate) {
+ StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributePredicate.value;
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
- AssetQuery.StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
+ StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeBuilder.append(stringPredicate.caseSensitive
? " and AX.VALUE #> '{value}' ->> " + i
: " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
@@ -1081,8 +1157,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
}
- } else if (attributePredicate.value instanceof AssetQuery.DateTimePredicate) {
- AssetQuery.DateTimePredicate dateTimePredicate = (AssetQuery.DateTimePredicate) attributePredicate.value;
+ } else if (attributePredicate.value instanceof DateTimePredicate) {
+ DateTimePredicate dateTimePredicate = (DateTimePredicate) attributePredicate.value;
attributeBuilder.append(" and to_timestamp(AX.VALUE #>> '{value}', ?)");
final int keyFormatPos = binders.size() + 1;
binders.add(st -> st.setString(keyFormatPos, dateTimePredicate.dateFormat));
@@ -1119,8 +1195,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(formatPos2, dateTimePredicate.dateFormat));
break;
}
- } else if (attributePredicate.value instanceof AssetQuery.NumberPredicate) {
- AssetQuery.NumberPredicate numberPredicate = (AssetQuery.NumberPredicate) attributePredicate.value;
+ } else if (attributePredicate.value instanceof NumberPredicate) {
+ NumberPredicate numberPredicate = (NumberPredicate) attributePredicate.value;
attributeBuilder.append(" and (AX.VALUE #>> '{value}')::numeric");
switch (numberPredicate.operator) {
case EQUALS:
@@ -1165,7 +1241,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
break;
}
- } else if (attributePredicate.value instanceof AssetQuery.ObjectValueKeyPredicate) {
+ } else if (attributePredicate.value instanceof ObjectValueKeyPredicate) {
ObjectValueKeyPredicate keyPredicate = (ObjectValueKeyPredicate) attributePredicate.value;
if (keyPredicate.negated) {
attributeBuilder.append(" and NOT(AX.VALUE #> '{value}' ?? ? ) ");
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java b/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java
deleted file mode 100644
index 7d57fae96..000000000
--- a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.notification;
-
-import com.google.auth.oauth2.GoogleCredentials;
-import com.google.firebase.FirebaseApp;
-import com.google.firebase.FirebaseOptions;
-import com.google.firebase.messaging.*;
-import org.openremote.container.Container;
-import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.notification.DeliveryStatus;
-import org.openremote.model.notification.DeviceNotificationToken;
-import org.openremote.model.util.TextUtil;
-
-import javax.persistence.EntityManager;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class FCMDeliveryService {
-
- private static final Logger LOG = Logger.getLogger(FCMDeliveryService.class.getName());
- public static final String FIREBASE_CONFIG_FILE = "FIREBASE_CONFIG_FILE";
- public static final int CONNECT_TIMEOUT_MILLIS = 3000;
- public static final int READ_TIMEOUT_MILLIS = 3000;
-
- protected boolean valid;
-
- public FCMDeliveryService(Container container) {
- this(
- container.getConfig().get(FIREBASE_CONFIG_FILE)
- );
- }
-
- public FCMDeliveryService(String firebaseConfigFilePath) {
-
- if (TextUtil.isNullOrEmpty(firebaseConfigFilePath)) {
- LOG.info(FIREBASE_CONFIG_FILE + " not defined, can not send FCM notifications");
- return;
- }
-
- if (!Files.isReadable(Paths.get(firebaseConfigFilePath))) {
- LOG.info(FIREBASE_CONFIG_FILE + " invalid path or file not readable");
- return;
- }
-
- try (InputStream is = Files.newInputStream(Paths.get(firebaseConfigFilePath))) {
- FirebaseOptions options = new FirebaseOptions.Builder()
- .setCredentials(GoogleCredentials.fromStream(is))
- .setConnectTimeout(CONNECT_TIMEOUT_MILLIS)
- .setReadTimeout(READ_TIMEOUT_MILLIS)
- .build();
-
- FirebaseApp.initializeApp(options);
- valid = true;
- } catch (Exception ex) {
- LOG.severe("Exception occurred whilst initialising FCM");
- }
- }
-
- public Consumer<EntityManager> deliverPendingToFCM(String userId, List<DeviceNotificationToken> deviceTokens) {
- if (!isValid()) {
- LOG.warning("FCM invalid configuration so ignoring");
- return null;
- }
-
- return entityManager -> {
- List<AlertNotification> pendingNotifications = entityManager.createQuery(
- "SELECT an FROM AlertNotification an WHERE an.userId = :userId and an.deliveryStatus = :deliveryStatus",
- AlertNotification.class
- ).setParameter("userId", userId).setParameter("deliveryStatus", DeliveryStatus.PENDING).getResultList();
-
- // If there are any pending notifications for the user
- if (pendingNotifications.size() > 0) {
- // If at least one of the user's devices received the pickup signal, it's queued
- if (sendPickupSignalThroughFCM(userId, deviceTokens)) {
- for (AlertNotification notification : pendingNotifications) {
- notification.setDeliveryStatus(DeliveryStatus.QUEUED);
- }
- }
- }
- };
- }
-
- /**
- * @return <code>true</code> if a signal was delivered to at least one device of the user.
- */
- protected boolean sendPickupSignalThroughFCM(String userId, List<DeviceNotificationToken> deviceTokens) {
- if (deviceTokens.size() == 0) {
- LOG.fine("No registered devices, can't deliver pending notifications of: " + userId);
- return false;
- }
-
- boolean success = false;
- for (DeviceNotificationToken deviceToken : deviceTokens) {
- LOG.fine("Sending FCM notification pickup message to: " + deviceToken);
- // Changed to behave like javadoc says
- success = sendMessage(FCMTargetType.DEVICE, deviceToken.getToken(), null, null, FCMMessagePriority.HIGH, null) || success;
- }
- if (success) {
- LOG.fine("Successfully delivered FCM pickup message for at least one device of: " + userId);
- } else {
- LOG.warning("Unsuccessful sending FCM pickup message for any device of: " + userId);
- }
- return success;
- }
-
- public boolean sendMessage(FCMTargetType targetType, String target, FCMNotification notification, Map<String, String> data, FCMMessagePriority priority, Integer timeToLiveSeconds) {
- if (!isValid()) {
- LOG.warning("FCM invalid configuration so ignoring");
- return false;
- }
-
- if (TextUtil.isNullOrEmpty(target)) {
- LOG.info("Invalid FCM message, the target is required and either notification and/or data must be set");
- return false;
- }
-
- Message.Builder builder = Message.builder();
-
- switch (targetType) {
- case DEVICE:
- builder.setToken(target);
- break;
- case TOPIC:
- builder.setTopic(target);
- break;
- case CONDITION:
- builder.setCondition(target);
- break;
- }
-
- AndroidConfig.Builder androidConfigBuilder = AndroidConfig.builder();
- ApnsConfig.Builder apnsConfigBuilder = ApnsConfig.builder();
- Aps.Builder apsBuilder = Aps.builder();
- WebpushConfig.Builder webpushConfigBuilder = WebpushConfig.builder();
-
- if (notification != null) {
- // Don't set basic notification on Android if there is data so even if app is in background we can show a custom notification
- // with actions that use the actions from the data
- if (data != null) {
- androidConfigBuilder.putData("or-title", notification.getTitle());
- androidConfigBuilder.putData("or-body", notification.getBody());
- }
-
- // Use alert dictionary for apns
- // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
- apsBuilder.setAlert(ApsAlert.builder().setTitle(notification.getTitle()).setBody(notification.getBody()).build())
- .setSound("default");
-
- webpushConfigBuilder.setNotification(new WebpushNotification(notification.getTitle(), notification.getBody()));
- }
-
- if (data != null) {
- builder.putAllData(data);
- if (notification == null) {
- apsBuilder.setContentAvailable(true);
- }
- }
-
- androidConfigBuilder.setPriority(priority == FCMMessagePriority.HIGH ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL);
- apnsConfigBuilder.putHeader("apns-priority", notification != null ? "10" : "5"); // Don't use 10 for data only
-
- // set the following APNS flag to allow console to customise the notification before delivery and to ensure delivery
- apsBuilder.setMutableContent(true);
-
- if (timeToLiveSeconds != null) {
- timeToLiveSeconds = Math.max(timeToLiveSeconds, 0);
- long timeToLiveMillis = timeToLiveSeconds * 1000;
- Date expirationDate = new Date(new Date().getTime() + timeToLiveMillis);
- long epochSeconds = Math.round(((float) expirationDate.getTime()) / 1000);
-
- apnsConfigBuilder.putHeader("apns-expiration", Long.toString(epochSeconds));
- androidConfigBuilder.setTtl(timeToLiveMillis);
- webpushConfigBuilder.putHeader("TTL", Integer.toString(timeToLiveSeconds));
- }
-
- apnsConfigBuilder.setAps(apsBuilder.build());
- builder.setAndroidConfig(androidConfigBuilder.build());
- builder.setApnsConfig(apnsConfigBuilder.build());
- builder.setWebpushConfig(webpushConfigBuilder.build());
-
- return sendMessage(builder.build());
- }
-
- public boolean sendMessage(Message message) {
- if (!isValid()) {
- LOG.warning("FCM invalid configuration so ignoring");
- return false;
- }
-
- boolean success = false;
-
- try {
- String response = FirebaseMessaging.getInstance().send(message);
- success = true;
- } catch (FirebaseMessagingException e) {
- LOG.log(Level.WARNING, "FCM send failed: " + e.getErrorCode(), e);
-
- // TODO: Implement backoff and blacklisting
-// switch (e.getErrorCode()) {
-// // Errors we cannot recover from - stop FCM to avoid blacklisting our app
-// case "invalid-argument":
-// case "authentication-error":
-// LOG.severe("FCM critical error so marking FCM as invalid no more messages will be sent");
-// setValid(false);
-// break;
-// case "server-unavailable":
-// case "internal-error":
-// break;
-// }
- }
-
- return success;
- }
-
- public synchronized boolean isValid() {
- return valid;
- }
-
- protected synchronized void setValid(boolean valid) {
- this.valid = valid;
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java b/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java
deleted file mode 100644
index 78426de5b..000000000
--- a/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.notification;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.openremote.model.value.ObjectValue;
-
-import java.util.Map;
-
-public class FCMMessage extends FCMBaseMessage {
-
- protected FCMNotification notification;
- protected boolean contentAvailable;
- protected boolean mutableContent;
- protected String priority;
- protected Map<String, String> data;
-
- public FCMMessage(FCMNotification notification, boolean contentAvailable, boolean mutableContent, String priority, String to) {
- super(to);
- this.notification = notification;
- this.contentAvailable = contentAvailable;
- this.mutableContent = mutableContent;
- this.priority = priority;
- }
-
- public FCMNotification getNotification() {
- return notification;
- }
-
- public void setNotification(FCMNotification notification) {
- this.notification = notification;
- }
-
- @JsonProperty("content_available")
- public boolean getContentAvailable() {
- return contentAvailable;
- }
-
- public void setContentAvailable(boolean contentAvailable) {
- this.contentAvailable = contentAvailable;
- }
-
- @JsonProperty("mutable_content")
- public boolean getMutableContent() {
- return mutableContent;
- }
-
- public void setMutableContent(boolean mutableContent) {
- this.mutableContent = mutableContent;
- }
-
- public String getPriority() {
- return priority;
- }
-
- public void setPriority(String priority) {
- this.priority = priority;
- }
-
- public Map<String, String> getData() {
- return data;
- }
-
- public void setData(Map<String, String> data) {
- this.data = data;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "notification=" + notification +
- ", contentAvailable=" + contentAvailable +
- ", mutableContent=" + mutableContent +
- ", priority='" + priority + '\'' +
- ", data='" + data + '\'' +
- '}';
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java
new file mode 100644
index 000000000..3cda37e6b
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.notification;
+
+import org.openremote.container.ContainerService;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.notification.AbstractNotificationMessage;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.NotificationSendResult;
+
+/**
+ * A {@link NotificationHandler} is responsible for sending compatible {@link AbstractNotificationMessage} messages to
+ * the specified target. Before a message is sent:
+ * <ol>
+ * <li>The {@link #isMessageValid} method will be called which allows the {@link NotificationHandler} to validate
+ * that the message is compatible and correctly structured.
+ * <li>The {@link #mapTarget} method will be called which allows the {@link NotificationHandler} to map the requested
+ * target to a target that is compatible with this handler.
+ * </ol>
+ */
+public interface NotificationHandler extends ContainerService {
+
+ /**
+ * The unique type name; it must correspond with the value set in {@link AbstractNotificationMessage#getType} so that
+ * {@link AbstractNotificationMessage}s can be mapped to a {@link NotificationHandler}.
+ */
+ String getTypeName();
+
+ /**
+ * Allows the handler to validate the specified {@link AbstractNotificationMessage}.
+ */
+ boolean isMessageValid(AbstractNotificationMessage message);
+
+ /**
+ * Map the requested target to one or more targets that are compatible with this handler; if there are no compatible
+ * targets then return null. If the requested target is already compatible then it can just be returned; handlers
+ * are free to determine how the requested target should be mapped (e.g. if requested {@link Notification.TargetType}
+ * was {@link Notification.TargetType#TENANT} and this handler only supports targets of type
+ * {@link Notification.TargetType#ASSET} where {@link AssetType} equals {@link AssetType#CONSOLE} then the handler
+ * needs to find all console assets that belong to the specified tenant).
+ */
+ Notification.Targets mapTarget(Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);
+
+ /**
+ * Send the specified {@link AbstractNotificationMessage} to the target; the target supplied would be a target
+ * previously returned by {@link #mapTarget}. It is the responsibility of the {@link NotificationHandler} to
+ * maintain any required cache to ensure this call is as performant as possible (i.e. the handler should avoid
+ * making excessive DB calls if possible).
+ * <p>
+ * The ID can be used by the {@link NotificationHandler} to update the delivered and/or acknowledged status of the notification
+ * by calling {@link NotificationService#setNotificationDelivered} or {@link NotificationService#setNotificationAcknowleged}
+ */
+ NotificationSendResult sendMessage(long id, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
new file mode 100644
index 000000000..07195177e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.notification;
+
+import org.openremote.model.notification.AbstractNotificationMessage;
+import org.openremote.model.notification.Notification;
+
+/**
+ * The reason why sending an {@link org.openremote.model.notification.Notification} failed.
+ */
+public class NotificationProcessingException extends RuntimeException {
+
+ public enum Reason {
+
+ /**
+ * Missing {@link Notification.Source}.
+ */
+ MISSING_SOURCE,
+
+ /**
+ * Missing {@link Notification}.
+ */
+ MISSING_NOTIFICATION,
+
+ /**
+ * Missing {@link AbstractNotificationMessage}.
+ */
+ MISSING_MESSAGE,
+
+ /**
+ * Missing {@link Notification.Targets}.
+ */
+ MISSING_TARGETS,
+
+ /**
+ * The {@link AbstractNotificationMessage} type is not supported.
+ */
+ UNSUPPORTED_MESSAGE_TYPE,
+
+ /**
+ * The actioner doesn't have sufficient access to send notifications to one or more specified targets.
+ */
+ INSUFFICIENT_ACCESS,
+
+ /**
+ * The message is deemed to be invalid as determined by {@link NotificationHandler#isMessageValid}.
+ */
+ INVALID_MESSAGE,
+
+ /**
+ * An error occurred whilst trying to map target IDs to actual targets.
+ */
+ ERROR_TARGET_MAPPING,
+
+ /**
+ * {@link NotificationHandler} failed to return any results.
+ */
+ SEND_FAILURE
+ }
+
+ final protected Reason reason;
+ final protected String message;
+
+ public NotificationProcessingException(Reason reason) {
+ this(reason, null);
+ }
+
+ public NotificationProcessingException(Reason reason, String message) {
+ this.reason = reason;
+ this.message = message;
+ }
+
+ public Reason getReason() {
+ return reason;
+ }
+
+ public String getReasonPhrase() {
+ return getReason() + (message != null ? " (" + message + ")": "");
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
index bece38741..221bd27b9 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
@@ -19,117 +19,194 @@
*/
package org.openremote.manager.notification;
+import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.web.WebResource;
-import org.openremote.model.notification.DeviceNotificationToken;
-import org.openremote.model.notification.NotificationResource;
+import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.http.RequestParams;
-import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.notification.DeliveryStatus;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.NotificationResource;
+import org.openremote.model.notification.SentNotification;
+import org.openremote.model.value.Value;
import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.logging.Logger;
-import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
-import static javax.ws.rs.core.Response.Status.FORBIDDEN;
+import static javax.ws.rs.core.Response.Status.*;
+import static org.openremote.model.notification.Notification.Source.CLIENT;
public class NotificationResourceImpl extends WebResource implements NotificationResource {
private static final Logger LOG = Logger.getLogger(NotificationResourceImpl.class.getName());
final protected NotificationService notificationService;
-
- public NotificationResourceImpl(NotificationService notificationService) {
+ final protected MessageBrokerService messageBrokerService;
+ final protected AssetStorageService assetStorageService;
+ final protected ManagerIdentityService managerIdentityService;
+
+ public NotificationResourceImpl(NotificationService notificationService,
+ MessageBrokerService messageBrokerService,
+ AssetStorageService assetStorageService,
+ ManagerIdentityService managerIdentityService) {
this.notificationService = notificationService;
+ this.messageBrokerService = messageBrokerService;
+ this.assetStorageService = assetStorageService;
+ this.managerIdentityService = managerIdentityService;
}
@Override
- public void storeDeviceToken(RequestParams requestParams, String deviceId, String token, String deviceType) {
- if (token == null || token.length() == 0 || deviceId == null || deviceId.length() == 0) {
- throw new WebApplicationException("Missing token or device identifier", BAD_REQUEST);
+ public SentNotification[] getNotifications(RequestParams requestParams, List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) {
+ try {
+ return notificationService.getNotifications(types, timestamp, tenantIds, userIds, assetIds).toArray(new SentNotification[0]);
+ } catch (IllegalArgumentException e) {
+ throw new WebApplicationException("Invalid criteria set", NOT_ACCEPTABLE);
}
- notificationService.storeDeviceToken(deviceId, getUserId(), token, deviceType);
}
@Override
- public List<DeviceNotificationToken> getDeviceTokens(RequestParams requestParams, String userId) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't get device tokens for user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ public void removeNotifications(RequestParams requestParams, List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) {
+ try {
+ notificationService.removeNotifications(types, timestamp, tenantIds, userIds, assetIds);
+ } catch (IllegalArgumentException e) {
+ throw new WebApplicationException("Invalid criteria set", NOT_ACCEPTABLE);
}
- return notificationService.findAllTokenForUser(userId);
}
@Override
- public void deleteDeviceToken(RequestParams requestParams, String userId, String deviceId) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't delete device token for user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ public void removeNotification(RequestParams requestParams, Long notificationId) {
+ if (notificationId == null) {
+ throw new WebApplicationException("Missing notification ID", BAD_REQUEST);
}
- notificationService.deleteDeviceToken(deviceId, userId);
- }
- @Override
- public void storeNotificationForCurrentUser(RequestParams requestParams, AlertNotification alertNotification) {
- if (alertNotification == null) {
- throw new WebApplicationException("Missing alertNotification", BAD_REQUEST);
- }
- notificationService.storeAndNotify(getUserId(), alertNotification);
+ notificationService.removeNotification(notificationId);
}
@Override
- public void storeNotificationForUser(RequestParams requestParams, String userId, AlertNotification alertNotification) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't store notification for user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ public void sendNotification(RequestParams requestParams, Notification notification) {
+
+ Map<String, Object> headers = new HashMap<>();
+ headers.put(Notification.HEADER_SOURCE, CLIENT);
+
+ if (isAuthenticated()) {
+ headers.put(Constants.AUTH_CONTEXT, getAuthContext());
}
- if (alertNotification == null) {
- throw new WebApplicationException("Missing AlertNotification entity", BAD_REQUEST);
+
+ Object result = messageBrokerService.getProducerTemplate().requestBodyAndHeaders(
+ NotificationService.NOTIFICATION_QUEUE, notification, headers);
+
+ if (result instanceof NotificationProcessingException) {
+ NotificationProcessingException processingException = (NotificationProcessingException) result;
+ switch (processingException.getReason()) {
+
+ case INSUFFICIENT_ACCESS:
+ throw new WebApplicationException(processingException.getMessage(), FORBIDDEN);
+ case MISSING_SOURCE:
+ case MISSING_NOTIFICATION:
+ case MISSING_MESSAGE:
+ case MISSING_TARGETS:
+ throw new WebApplicationException(processingException.getMessage(), BAD_REQUEST);
+ case UNSUPPORTED_MESSAGE_TYPE:
+ throw new IllegalStateException(processingException);
+ }
}
- notificationService.storeAndNotify(userId, alertNotification);
}
@Override
- public AlertNotification[] getNotificationsOfUser(RequestParams requestParams, String userId) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't get notifications of user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ public void notificationDelivered(RequestParams requestParams, String targetId, Long notificationId) {
+ if (notificationId == null) {
+ throw new WebApplicationException("Missing notification ID", BAD_REQUEST);
}
- return notificationService.getNotificationsOfUser(userId).toArray(new AlertNotification[0]);
+
+ SentNotification sentNotification = notificationService.getSentNotification(notificationId);
+ verifyAccess(sentNotification, targetId);
+ notificationService.setNotificationDelivered(notificationId);
}
@Override
- public void removeNotificationsOfUser(RequestParams requestParams, String userId) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't remove notifications of user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ public void notificationAcknowledged(RequestParams requestParams, String targetId, Long notificationId, Value acknowledgement) {
+ if (notificationId == null) {
+ throw new WebApplicationException("Missing notification ID", BAD_REQUEST);
}
- notificationService.removeNotificationsOfUser(userId);
+
+ SentNotification sentNotification = notificationService.getSentNotification(notificationId);
+ verifyAccess(sentNotification, targetId);
+ notificationService.setNotificationAcknowleged(notificationId, acknowledgement.toString());
}
- @Override
- public void removeNotification(RequestParams requestParams, String userId, Long id) {
- if (!isSuperUser()) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't remove notification of user: " + userId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ protected void verifyAccess(SentNotification sentNotification, String targetId) {
+ if (sentNotification == null) {
+ LOG.fine("DENIED: Notification not found");
+ throw new WebApplicationException(NOT_FOUND);
}
- notificationService.removeNotification(userId, id);
- }
- @Override
- public List<AlertNotification> getQueuedNotificationsOfCurrentUser(RequestParams requestParams) {
- return notificationService.getNotificationsOfUser(getUserId(), DeliveryStatus.QUEUED);
- }
+ if (sentNotification.getTargetId() == null || !sentNotification.getTargetId().equals(targetId)) {
+ LOG.fine("DENIED: Notification target ID doesn't match supplied target ID");
+ throw new WebApplicationException(NOT_FOUND);
+ }
- @Override
- public void ackNotificationOfCurrentUser(RequestParams requestParams, Long id) {
- if (id == null) {
- throw new WebApplicationException("Missing alert id", BAD_REQUEST);
+ if (isSuperUser()) {
+ LOG.finest("ALLOWED: Request from super user so allowing");
+ return;
}
- if (!isSuperUser() && !notificationService.isQueuedNotificationForUser(id, getUserId())) {
- throw new WebApplicationException(FORBIDDEN);
+
+ // Anonymous requests can only be actioned against public assets
+ if (!isAuthenticated()) {
+ if (sentNotification.getTarget() != Notification.TargetType.ASSET) {
+ LOG.fine("DENIED: Anonymous request to update a notification not sent to a public asset");
+ throw new WebApplicationException("Anonymous request can only update public assets", FORBIDDEN);
+ }
+
+ // Check asset is public read amd not linked to any users
+ Asset asset = assetStorageService.find(sentNotification.getTargetId(), false, BaseAssetQuery.Access.PUBLIC_READ);
+ if (asset == null) {
+ LOG.fine("DENIED: Anonymous request to update a notification sent to an asset that doesn't exist or isn't public");
+ throw new WebApplicationException("Anonymous request can only update public assets not linked to a user", FORBIDDEN);
+ }
+ if (assetStorageService.isUserAsset(asset.getId())) {
+ LOG.fine("DENIED: Anonymous request to update a notification sent to an asset that is linked to one or more users");
+ throw new WebApplicationException("Anonymous request can only update public assets not linked to a user", FORBIDDEN);
+ }
+ } else {
+ // Regular users can only update notifications sent to them or assets in their realm
+ // Restricted users can only update notifications sent to them or assets linked to them
+ boolean isRestrictedUser = managerIdentityService.getIdentityProvider().isRestrictedUser(getUserId());
+ switch (sentNotification.getTarget()) {
+
+ case TENANT:
+ // What does it mean when a notification has been sent to a tenant - who can acknowledge them?
+ if (isRestrictedUser) {
+ LOG.fine("DENIED: Restricted user request to update a notification sent to a tenant");
+ throw new WebApplicationException("Restricted users cannot update a tenant notification", FORBIDDEN);
+ }
+ break;
+ case USER:
+ if (!sentNotification.getTargetId().equals(getUserId())) {
+ LOG.fine("DENIED: User request to update a notification sent to a different user");
+ throw new WebApplicationException("Regular and restricted users can only update user notifications sent to themselves", FORBIDDEN);
+ }
+ break;
+ case ASSET:
+ Asset asset = assetStorageService.find(sentNotification.getTargetId(), false);
+ if (asset == null) {
+ LOG.fine("DENIED: User request to update a notification sent to an asset that doesn't exist");
+ throw new WebApplicationException("Asset not found", NOT_FOUND);
+ }
+ if (!asset.getRealmId().equals(managerIdentityService.getIdentityProvider().getTenantForRealm(getAuthenticatedRealm()).getId())) {
+ LOG.fine("DENIED: User request to update a notification sent to an asset that is in another realm");
+ throw new WebApplicationException("Asset not in users realm", FORBIDDEN);
+ }
+ if (isRestrictedUser && !assetStorageService.isUserAsset(getUserId(), asset.getId())) {
+ LOG.fine("DENIED: Restricted user request to update a notification sent to an asset that isn't linked to themselves");
+ throw new WebApplicationException("Asset not linked to restricted user", FORBIDDEN);
+ }
+ break;
+ }
}
- notificationService.setAcknowledged(id);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
index 86d342b80..a25f43cf5 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -19,279 +19,574 @@
*/
package org.openremote.manager.notification;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.openremote.agent.protocol.Protocol;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceService;
+import org.openremote.container.security.AuthContext;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.asset.BaseAssetQuery;
-import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.console.ConsoleConfiguration;
-import org.openremote.model.console.ConsoleProvider;
-import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.notification.DeliveryStatus;
-import org.openremote.model.notification.DeviceNotificationToken;
-import org.openremote.model.user.UserQuery;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.NotificationSendResult;
+import org.openremote.model.notification.SentNotification;
import org.openremote.model.util.TextUtil;
+import org.openremote.model.util.TimeUtil;
-import javax.persistence.EntityManager;
import javax.persistence.Query;
+import javax.persistence.TypedQuery;
+import java.time.ZonedDateTime;
+import java.time.temporal.TemporalField;
+import java.time.temporal.WeekFields;
import java.util.*;
-import java.util.function.Consumer;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
-public class NotificationService implements ContainerService {
+import static org.openremote.manager.notification.NotificationProcessingException.Reason.*;
+import static org.openremote.model.notification.Notification.HEADER_SOURCE;
+import static org.openremote.model.notification.Notification.Source.INTERNAL;
+
+// TODO Implement notification purging - configurable MAX_AGE for notifications?
+public class NotificationService extends RouteBuilder implements ContainerService {
private static final Logger LOG = Logger.getLogger(NotificationService.class.getName());
+ public static final String NOTIFICATION_QUEUE = "seda://NotificationQueue?waitForTaskToComplete=IfReplyExpected&timeout=10000&purgeWhenStopping=true&discardIfNoConsumers=false&size=25000";
+ protected static final TemporalField WEEK_FIELD_ISO = WeekFields.of(Locale.FRANCE).dayOfWeek(); // Always use ISO for consistency
+
protected TimerService timerService;
protected PersistenceService persistenceService;
- protected FCMDeliveryService fcmDeliveryService;
protected AssetStorageService assetStorageService;
+ protected ManagerIdentityService identityService;
+ protected MessageBrokerService messageBrokerService;
+ protected Map<String, NotificationHandler> notificationHandlerMap;
+
+ public NotificationService() {
+ // Create notification handlers here to facilitate testing
+ notificationHandlerMap = new HashMap<>();
+ NotificationHandler pushHandler = new PushNotificationHandler();
+ notificationHandlerMap.put(pushHandler.getTypeName(), pushHandler);
+
+ }
@Override
public void init(Container container) throws Exception {
this.timerService = container.getService(TimerService.class);
this.persistenceService = container.getService(PersistenceService.class);
this.assetStorageService = container.getService(AssetStorageService.class);
- this.fcmDeliveryService = new FCMDeliveryService(container);
+ this.identityService = container.getService(ManagerIdentityService.class);
+ this.messageBrokerService = container.getService(MessageBrokerService.class);
+ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
+
+ // Init notification handlers
+ for (NotificationHandler handler : notificationHandlerMap.values()) {
+ handler.init(container);
+ }
container.getService(WebService.class).getApiSingletons().add(
- new NotificationResourceImpl(this)
+ new NotificationResourceImpl(this,
+ container.getService(MessageBrokerService.class),
+ container.getService(AssetStorageService.class),
+ container.getService(ManagerIdentityService.class))
);
}
@Override
public void start(Container container) throws Exception {
+ for (NotificationHandler handler : notificationHandlerMap.values()) {
+ handler.start(container);
+ }
}
@Override
public void stop(Container container) throws Exception {
+ for (NotificationHandler handler : notificationHandlerMap.values()) {
+ handler.stop(container);
+ }
}
- public void storeDeviceToken(String deviceId, String userId, String token, String deviceType) {
- persistenceService.doTransaction(entityManager -> {
- DeviceNotificationToken.Id id = new DeviceNotificationToken.Id(deviceId, userId);
- DeviceNotificationToken deviceToken = new DeviceNotificationToken(id, token, deviceType);
- deviceToken.setUpdatedOn(new Date(timerService.getCurrentTimeMillis()));
- entityManager.merge(deviceToken);
- });
- }
-
- public void deleteDeviceToken(String deviceId, String userId) {
- persistenceService.doTransaction(entityManager -> {
- DeviceNotificationToken.Id id = new DeviceNotificationToken.Id(deviceId, userId);
- DeviceNotificationToken deviceToken = entityManager.find(DeviceNotificationToken.class, id);
- if (deviceToken != null) {
- entityManager.remove(deviceToken);
- }
- });
- }
-
- public Optional<DeviceNotificationToken> findDeviceToken(String deviceId, String userId) {
- return persistenceService.doReturningTransaction(entityManager -> {
- DeviceNotificationToken.Id id = new DeviceNotificationToken.Id(deviceId, userId);
- DeviceNotificationToken deviceToken = entityManager.find(DeviceNotificationToken.class, id);
- return Optional.ofNullable(deviceToken);
- });
- }
-
- public List<DeviceNotificationToken> findAllTokenForUser(String userId) {
- return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
- "SELECT dnt FROM DeviceNotificationToken dnt WHERE dnt.id.userId =:userId order by dnt.updatedOn desc", DeviceNotificationToken.class
- ).setParameter("userId", userId).getResultList());
- }
-
- public boolean isFcmEnabled() {
- return fcmDeliveryService.isValid();
- }
-
- public boolean sendFcmMessage(FCMTargetType targetType, String target, FCMNotification notification, Map<String, String> data, FCMMessagePriority priority, Integer expiration) {
- return fcmDeliveryService.sendMessage(targetType, target, notification, data, priority, expiration);
- }
+ @Override
+ public void configure() throws Exception {
- //TODO: Unify the notification service to support push, email, SMS, etc.
- public void notifyConsole(String consoleId, AlertNotification alertNotification) {
- notifyConsole(consoleId, alertNotification, null);
- }
+ from(NOTIFICATION_QUEUE)
+ .routeId("NotificationQueueProcessor")
+ .doTry()
+ .process(exchange -> {
+ Notification notification = exchange.getIn().getBody(Notification.class);
- public void notifyConsoleSilently(String consoleId, Map<String, String> data) {
- notifyConsole(consoleId, null, data);
- }
+ if (notification == null) {
+ throw new NotificationProcessingException(MISSING_NOTIFICATION, "Notification must be set");
+ }
- public void notifyConsole(String consoleId, AlertNotification alertNotification, Map<String, String> data) {
- AssetQuery consoleQuery = new AssetQuery()
- .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
- false,
- AttributeType.CONSOLE_PROVIDERS.getName()))
- .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
- new BaseAssetQuery.ObjectValueKeyPredicate("push"))
- .id(consoleId);
+ LOG.finest("Processing: " + notification.getName());
+ if (notification.getMessage() == null) {
+ throw new NotificationProcessingException(MISSING_MESSAGE, "Notification message must be set");
+ }
- Asset console = assetStorageService.find(consoleQuery);
- if (console == null) {
- LOG.warning("Console cannot be found or doesn't support push notifications");
- return;
- }
+ if (notification.getTargets() == null || notification.getTargets().getType() == null || notification.getTargets().getIds() == null || notification.getTargets().getIds().length == 0) {
+ throw new NotificationProcessingException(MISSING_TARGETS, "Notification targets must be set");
+ }
- ConsoleProvider consolePushProvider = ConsoleConfiguration.getConsoleProvider(console, "push")
- .orElseThrow(() -> new IllegalStateException("Console push provider is not valid"));
+ Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Notification.Source.class);
- String pushProviderVersion = consolePushProvider.getVersion();
+ if (source == null) {
+ throw new NotificationProcessingException(MISSING_SOURCE);
+ }
- if ("fcm".equals(pushProviderVersion)) {
- if (consolePushProvider.getData() == null || !consolePushProvider.getData().getString("token")
- .map(token -> TextUtil.isNullOrEmpty(token) ? null : token).isPresent()) {
- LOG.warning("Console 'fcm' push provider doesn't contain an FCM token");
- return;
- }
+ // Validate handler and message
+ NotificationHandler handler = notificationHandlerMap.get(notification.getMessage().getType());
+ if (handler == null) {
+ throw new NotificationProcessingException(UNSUPPORTED_MESSAGE_TYPE, "No handler for message type: " + notification.getMessage().getType());
+ }
+ if (!handler.isMessageValid(notification.getMessage())) {
+ throw new NotificationProcessingException(INVALID_MESSAGE);
+ }
- String token = consolePushProvider.getData().getString("token").orElse(null);
+ // Validate access and map targets to handler compatible targets
+ String realmId = null;
+ String userId = null;
+ String assetId = null;
+ AtomicReference<String> sourceId = new AtomicReference<>();
+ boolean isSuperUser = false;
+ boolean isRestrictedUser = false;
+
+ switch (source) {
+ case INTERNAL:
+ isSuperUser = true;
+ break;
+
+ case CLIENT:
+
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ if (authContext == null) {
+ // Anonymous clients cannot send notifications
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ realmId = identityService.getIdentityProvider().getTenantForRealm(authContext.getAuthenticatedRealm()).getId();
+ userId = authContext.getUserId();
+ sourceId.set(userId);
+ isSuperUser = authContext.isSuperUser();
+ isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());
+ break;
+
+ case GLOBAL_RULESET:
+ isSuperUser = true;
+ break;
+
+ case TENANT_RULESET:
+ realmId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);
+ sourceId.set(realmId);
+ break;
+
+ case ASSET_RULESET:
+ assetId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);
+ sourceId.set(assetId);
+ Asset asset = assetStorageService.find(assetId, false);
+ realmId = asset.getRealmId();
+ break;
+ }
- FCMNotification notification = null;
- if (alertNotification != null) {
- notification = new FCMNotification(alertNotification.getTitle(), alertNotification.getMessage());
- if (data == null) {
- data = new HashMap<>();
+ LOG.info("Sending notification from '" + source + ":" + sourceId.get() + "': " + notification);
+
+ // Check access permissions
+ checkAccess(notification.getTargets(), realmId, userId, isSuperUser, isRestrictedUser, assetId);
+
+ // Map targets to handler compatible targets
+ List<Notification.Targets> mappedTargetsList = Arrays.stream(notification.getTargets().getIds())
+ .map(targetId -> {
+ Notification.Targets mappedTargets = handler.mapTarget(notification.getTargets().getType(), targetId, notification.getMessage());
+ if (mappedTargets == null || mappedTargets.getIds() == null || mappedTargets.getIds().length == 0) {
+ LOG.finest("Failed to map target using '" + handler.getClass().getSimpleName() + "' handler: "
+ + notification.getTargets().getType() + ":" + targetId);
+ }
+ return mappedTargets;
+ })
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
+
+ if (mappedTargetsList.isEmpty()) {
+ // TODO: Should the entire notification send request fail if any mappings fail?
+ throw new NotificationProcessingException(ERROR_TARGET_MAPPING, "No mapped targets");
}
- if (alertNotification.getActions() != null && !alertNotification.getActions().isEmpty()) {
- data.put("actions", alertNotification.getActions().toJson());
+ // Filter targets based on repeat frequency
+ Long timestamp = getRepeatAfterTimestamp(notification);
+
+ if (timestamp != null) {
+ mappedTargetsList.forEach(
+ targets ->
+ targets.setIds(
+ Arrays.stream(targets.getIds()).filter(
+ targetId -> !okToSendNotification(source,
+ sourceId.get(),
+ targets.getType(),
+ targetId,
+ notification.getName(),
+ timestamp))
+ .toArray(String[]::new)
+ ));
}
- }
- // Push alert directly inside the FCM message
- fcmDeliveryService.sendMessage(
- FCMTargetType.DEVICE,
- token,
- notification,
- data,
- FCMMessagePriority.HIGH,
- 0 // 0 TTL gives best performance and this is assuming notifications are time critical
- );
- } else {
- LOG.warning("Unsupported push provider version: " + pushProviderVersion);
- }
+ // Send message to each applicable target
+ mappedTargetsList.forEach(
+ targets -> {
+
+ if (targets.getIds() != null && targets.getIds().length > 0) {
+
+ Arrays.stream(targets.getIds()).forEach(targetId ->
+
+ persistenceService.doTransaction(em -> {
+
+ // commit the notification first to get the ID
+ SentNotification sentNotification = new SentNotification()
+ .setName(notification.getName())
+ .setType(notification.getMessage().getType())
+ .setMessage(notification.getMessage().toValue())
+ .setSource(source)
+ .setSourceId(sourceId.get())
+ .setTarget(targets.getType())
+ .setTargetId(targetId);
+ sentNotification = em.merge(sentNotification);
+ long id = sentNotification.getId();
+
+ try {
+ NotificationSendResult result = handler.sendMessage(id,
+ targets.getType(),
+ targetId,
+ notification.getMessage());
+
+ if (result.isSuccess()) {
+ LOG.fine("Notification sent: " + targets.getType() + ":" + targetId);
+ } else {
+ LOG.warning("Notification failed: " + targets.getType() + ":" + targetId + ", reason=" + result.getMessage());
+ sentNotification.setError(TextUtil.isNullOrEmpty(result.getMessage()) ? "Unknown error" : result.getMessage());
+ em.merge(sentNotification);
+ }
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE,
+ "Notification handler threw and exception whilst sending notification",
+ e);
+ sentNotification.setError(TextUtil.isNullOrEmpty(e.getMessage()) ? "Unknown error" : e.getMessage());
+ em.merge(sentNotification);
+ throw e;
+ }
+ })
+ );
+ } else {
+ LOG.info("Notification target contains no target IDs so ignoring");
+ }
+ });
+ })
+ .endDoTry()
+ .doCatch(NotificationProcessingException.class)
+ .process(handleNotificationProcessingException(LOG));
}
- public void storeAndNotify(String userId, AlertNotification notification) {
- notification.setUserId(userId);
- notification.setDeliveryStatus(DeliveryStatus.PENDING);
- persistenceService.doTransaction(entityManager -> entityManager.merge(notification));
+ public void sendNotification(Notification notification) throws NotificationProcessingException {
+ sendNotification(notification, INTERNAL, null);
+ }
- // Try to queue through FCM in a separate transaction
- Consumer<EntityManager> fcmMessageGenerator = fcmDeliveryService.deliverPendingToFCM(userId, findAllTokenForUser(userId));
- if (fcmMessageGenerator != null) {
- persistenceService.doTransaction(fcmMessageGenerator);
- }
+ public void sendNotification(Notification notification, Notification.Source source, String sourceId) throws NotificationProcessingException {
+ Map<String, Object> headers = new HashMap<>();
+ headers.put(Notification.HEADER_SOURCE, source);
+ headers.put(Notification.HEADER_SOURCE_ID, sourceId);
+ messageBrokerService.getProducerTemplate().sendBodyAndHeaders(NotificationService.NOTIFICATION_QUEUE, notification, headers);
}
- public List<AlertNotification> getNotificationsOfUser(String userId, DeliveryStatus deliveryStatus) {
- return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
- "SELECT an FROM AlertNotification an WHERE an.userId =:userId and an.deliveryStatus = :deliveryStatus order by an.createdOn desc",
- AlertNotification.class
- ).setParameter("userId", userId).setParameter("deliveryStatus", deliveryStatus).getResultList());
+ public void setNotificationDelivered(long id) {
+ setNotificationDelivered(id, timerService.getCurrentTimeMillis());
}
- public List<AlertNotification> getNotificationsOfUser(String userId) {
- return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
- "SELECT an FROM AlertNotification an WHERE an.userId = :userId order by an.createdOn desc",
- AlertNotification.class
- ).setParameter("userId", userId).getResultList());
+ public void setNotificationDelivered(long id, long timestamp) {
+ persistenceService.doTransaction(entityManager -> {
+ Query query = entityManager.createQuery("UPDATE Notification SET deliveryOn=:timestamp WHERE id =:id");
+ query.setParameter("id", id);
+ query.setParameter("timestamp", timestamp);
+ query.executeUpdate();
+ });
}
- public boolean isQueuedNotificationForUser(Long id, String userId) {
- return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
- "SELECT count(an) FROM AlertNotification an WHERE an.id = :alertId and an.userId =:userId and an.deliveryStatus = :deliveryStatus"
- , Long.class
- ).setParameter("alertId", id).setParameter("userId", userId).setParameter("deliveryStatus", DeliveryStatus.QUEUED).getSingleResult() > 0);
+ public void setNotificationAcknowleged(long id, String acknowledgement) {
+ setNotificationAcknowleged(id, acknowledgement, timerService.getCurrentTimeMillis());
}
- public void setAcknowledged(Long id) {
+ public void setNotificationAcknowleged(long id, String acknowledgement, long timestamp) {
persistenceService.doTransaction(entityManager -> {
- Query query = entityManager.createQuery("UPDATE AlertNotification SET deliveryStatus=:status WHERE id =:id");
+ Query query = entityManager.createQuery("UPDATE Notification SET acknowledgedOn=:timestamp, acknowledgement=:acknowledgement WHERE id =:id");
query.setParameter("id", id);
- query.setParameter("status", DeliveryStatus.ACKNOWLEDGED);
+ query.setParameter("timestamp", timestamp);
+ query.setParameter("acknowledgement", acknowledgement);
query.executeUpdate();
- // TODO Who is cleaning up the acknowledged notifications?
});
}
- public void removeNotificationsOfUser(String userId) {
- persistenceService.doTransaction(entityManager -> entityManager
- .createQuery("delete AlertNotification an where an.userId = :userId")
- .setParameter("userId", userId)
- .executeUpdate()
- );
+ public SentNotification getSentNotification(Long notificationId) {
+ return persistenceService.doReturningTransaction(em -> em.find(SentNotification.class, notificationId));
}
- public void removeNotification(String userId, Long id) {
- persistenceService.doTransaction(entityManager -> entityManager
- .createQuery("delete AlertNotification an where an.userId = :userId and an.id = :id")
- .setParameter("userId", userId).setParameter("id", id)
- .executeUpdate()
- );
+ public List<SentNotification> getNotifications(List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {
+ StringBuilder builder = new StringBuilder();
+ builder.append("select Notification n where 1=1");
+ List<Object> parameters = new ArrayList<>();
+ processCriteria(builder, parameters, types, timestamp, tenantIds, userIds, assetIds);
+
+ return persistenceService.doReturningTransaction(entityManager -> {
+ TypedQuery<SentNotification> query = entityManager.createQuery(builder.toString(), SentNotification.class);
+ // Parameters should be 1 based but bug in hibernate means 0 based
+ IntStream.range(0, parameters.size())
+ .forEach(i -> query.setParameter(i, parameters.get(i)));
+ return query.getResultList();
+ });
}
- public List<String> findAllUsersWithToken() {
- return persistenceService.doReturningTransaction(entityManager ->
- entityManager.createQuery("SELECT DISTINCT dnt.id.userId FROM DeviceNotificationToken dnt", String.class).getResultList()
+ public void removeNotification(Long id) {
+ persistenceService.doTransaction(entityManager -> entityManager
+ .createQuery("delete Notification n where n.id = :id")
+ .setParameter("id", id)
+ .executeUpdate()
);
}
- @SuppressWarnings("unchecked")
- public List<String> findAllUsersWithToken(UserQuery userQuery) {
- return persistenceService.doReturningTransaction(entityManager -> {
- Query query = entityManager.createQuery("SELECT DISTINCT dnt.id.userId " + buildFromString(userQuery) + buildWhereString(userQuery));
+ public void removeNotifications(List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {
- // TODO: improve way this is set, should be part of buildWhereString + some other operation, see AssetStorageService
- if (userQuery.tenantPredicate != null) {
- query.setParameter("realmId", userQuery.tenantPredicate.realmId);
- }
- if (userQuery.assetPredicate != null) {
- query.setParameter("assetId", userQuery.assetPredicate.id);
- }
+ StringBuilder builder = new StringBuilder();
+ builder.append("delete Notification n where 1=1");
+ List<Object> parameters = new ArrayList<>();
+ processCriteria(builder, parameters, types, timestamp, tenantIds, userIds, assetIds);
- return query.getResultList();
+ persistenceService.doTransaction(entityManager -> {
+ Query query = entityManager.createQuery(builder.toString());
+ // Parameters should be 1 based but bug in hibernate means 0 based
+ IntStream.range(0, parameters.size())
+ .forEach(i -> query.setParameter(i, parameters.get(i)));
+ query.executeUpdate();
});
}
- protected String buildFromString(UserQuery query) {
- StringBuilder sb = new StringBuilder();
+ protected void processCriteria(StringBuilder builder, List<Object> parameters, List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) {
+ boolean hasTypes = types != null && !types.isEmpty();
+ boolean hasTenants = tenantIds != null && !tenantIds.isEmpty();
+ boolean hasUsers = userIds != null && !userIds.isEmpty();
+ boolean hasAssets = assetIds != null && !assetIds.isEmpty();
+ int counter = 0;
+
+ if (hasTypes) {
+ counter++;
+ }
+ if (hasTenants) {
+ counter++;
+ }
+ if (hasUsers) {
+ counter++;
+ }
+ if (hasAssets) {
+ counter++;
+ }
+
+ if (timestamp == null && counter == 0) {
+ LOG.info("No filters set for remove notifications request so not allowed");
+ throw new IllegalArgumentException("No criteria specified");
+ }
+
+ if (counter > 1) {
+ throw new IllegalArgumentException("Too many criteria specified");
+ }
+
+ if (hasTypes) {
+ builder.append(" AND n.target IN ?")
+ .append(parameters.size() + 1);
+ parameters.add(types);
+ }
+
+ if (hasTenants) {
+ builder.append(" AND n.target = ?")
+ .append(parameters.size() + 1)
+ .append(" AND n.target_id IN ?")
+ .append(parameters.size() + 2);
+ parameters.add(Notification.TargetType.TENANT);
+ parameters.add(tenantIds);
+ }
- sb.append("FROM DeviceNotificationToken dnt ");
+ if (hasUsers) {
+ builder.append(" AND n.target = ?")
+ .append(parameters.size() + 1)
+ .append(" AND n.target_id IN ?")
+ .append(parameters.size() + 2);
- if (query.tenantPredicate != null) {
- sb.append("join User u on u.id = dnt.id.userId");
+ parameters.add(Notification.TargetType.USER);
+ parameters.add(userIds);
}
- if (query.assetPredicate != null) {
- sb.append("join UserAsset ua on ua.id.userId = dnt.id.userId ");
+
+ if (hasAssets) {
+ builder.append(" AND n.target = ?")
+ .append(parameters.size() + 1)
+ .append("AND n.target_id ANY ?")
+ .append(parameters.size() + 2);
+
+ parameters.add(Notification.TargetType.ASSET);
+ parameters.add(assetIds);
}
- return sb.toString();
+ if (timestamp != null) {
+ builder.append(" n.sent_on <= ?")
+ .append(parameters.size() + 1);
+
+ parameters.add(timestamp);
+ }
}
- protected String buildWhereString(UserQuery query) {
- StringBuilder sb = new StringBuilder();
+ protected Long getRepeatAfterTimestamp(Notification notification) {
+ Long timestamp = null;
+
+ if (TextUtil.isNullOrEmpty(notification.getName())) {
+ return null;
+ }
+
+ if (notification.getRepeatFrequency() != null) {
+ ZonedDateTime dateTime = timerService.getNow()
+ .withMinute(0)
+ .withHour(0)
+ .withSecond(0);
+
+ switch (notification.getRepeatFrequency()) {
+
+ case ALWAYS:
+ break;
+ case ONCE:
+ timestamp = 0L;
+ break;
+ case DAILY:
+ timestamp = dateTime.toInstant().toEpochMilli();
+ break;
+ case WEEKLY:
+ timestamp = dateTime.with(WEEK_FIELD_ISO, 1).toInstant().toEpochMilli();
+ break;
+ case MONTHLY:
+ timestamp = dateTime.withDayOfMonth(1).toInstant().toEpochMilli();
+ break;
+ case ANNUALLY:
+ timestamp = dateTime.withDayOfYear(1).toInstant().toEpochMilli();
+ break;
+ }
+ } else if (!TextUtil.isNullOrEmpty(notification.getRepeatInterval())) {
+ timestamp = timerService.getCurrentTimeMillis() - TimeUtil.parseTimeString(notification.getRepeatInterval());
+ }
+
+ return timestamp;
+ }
- sb.append(" WHERE 1 = 1 ");
+ @SuppressWarnings("unchecked")
+ protected void checkAccess(Notification.Targets targets, String realmId, String userId, boolean isSuperUser, boolean isRestrictedUser, String assetId) throws NotificationProcessingException {
- if (query.tenantPredicate != null) {
- sb.append("AND u.realmId = :realmId");
+ if (isSuperUser) {
+ return;
}
- if (query.assetPredicate != null) {
- sb.append("AND ua.id.assetId = :assetId ");
+
+ switch (targets.getType()) {
+
+ case TENANT:
+ // Only super user can send notifications to whole tenant
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+
+ case USER:
+ if (TextUtil.isNullOrEmpty(realmId) || isRestrictedUser) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Requester must be in the same realm as all target users
+ boolean realmMatch = Arrays.stream(identityService.getIdentityProvider().getUsers(Arrays.asList(targets.getIds())))
+ .allMatch(user -> realmId.equals(user.getRealmId()));
+
+ if (!realmMatch) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
+ }
+ break;
+
+ case ASSET:
+ if (TextUtil.isNullOrEmpty(realmId)) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // If requestor is restricted user check all target assets are linked to that user
+ if (isRestrictedUser && !assetStorageService.isUserAssets(userId, Arrays.asList(targets.getIds()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be linked to the requesting restricted user");
+ }
+
+ // Target assets must be in the same realm as requestor
+ if (!assetStorageService.isRealmAssets(realmId, Arrays.asList(targets.getIds()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
+ }
+
+ // Target assets must be descendants of the requesting asset
+ if (!TextUtil.isNullOrEmpty(assetId)) {
+ if (!assetStorageService.isDescendantAssets(assetId, Arrays.asList(targets.getIds()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be descendants of the requesting asset");
+ }
+ }
+ break;
}
+ }
- return sb.toString();
+ protected boolean okToSendNotification(Notification.Source source, String sourceId, Notification.TargetType target, String targetId, String name, long timestamp) {
+ return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
+ "SELECT COUNT(n) FROM NOTIFICATION n WHERE n.source =:source AND n.source_id =:sourceId AND n.target =:target AND n.target_id =:targetId AND n.name =:name AND n.sent_on >=:timestamp", Long.class)
+ .setParameter("source", source)
+ .setParameter("sourceId", sourceId)
+ .setParameter("target", target)
+ .setParameter("targetId", targetId)
+ .setParameter("name", name)
+ .setParameter("timestamp", timestamp)
+ .getSingleResult() == 0L);
}
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{}";
+ protected static Processor handleNotificationProcessingException(Logger logger) {
+ return exchange -> {
+ Notification notification = exchange.getIn().getBody(Notification.class);
+ Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
+
+ StringBuilder error = new StringBuilder();
+
+ Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, "unknown source", Notification.Source.class);
+ if (source != null) {
+ error.append("Error processing from ").append(source);
+ }
+
+ String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);
+ if (protocolName != null) {
+ error.append(" (protocol: ").append(protocolName).append(")");
+ }
+
+ // TODO Better exception handling - dead letter queue?
+ if (exception instanceof NotificationProcessingException) {
+ NotificationProcessingException processingException = (NotificationProcessingException) exception;
+ error.append(" - ").append(processingException.getReasonPhrase());
+ error.append(": ").append(notification.toString());
+ logger.warning(error.toString());
+ } else {
+ error.append(": ").append(notification.toString());
+ logger.log(Level.WARNING, error.toString(), exception);
+ }
+
+ // Make the exception available if MEP is InOut
+ exchange.getOut().setBody(exception);
+ };
}
+ protected List<String> findAllUsersWithToken() {
+ return persistenceService.doReturningTransaction(entityManager ->
+ entityManager.createQuery("SELECT DISTINCT dnt.id.userId FROM DeviceNotificationToken dnt", String.class).getResultList()
+ );
+ }
}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
new file mode 100644
index 000000000..8504ede98
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -0,0 +1,495 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.notification;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.firebase.FirebaseApp;
+import com.google.firebase.FirebaseOptions;
+import com.google.firebase.messaging.*;
+import org.apache.camel.builder.RouteBuilder;
+import org.openremote.container.Container;
+import org.openremote.container.message.MessageBrokerSetupService;
+import org.openremote.container.persistence.PersistenceEvent;
+import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.AttributeType;
+import org.openremote.model.console.ConsoleConfiguration;
+import org.openremote.model.console.ConsoleProvider;
+import org.openremote.model.notification.AbstractNotificationMessage;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.NotificationSendResult;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.filter.ObjectValueKeyPredicate;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
+import org.openremote.model.util.TextUtil;
+
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+
+import static org.openremote.container.concurrent.GlobalLock.withLock;
+import static org.openremote.container.persistence.PersistenceEvent.*;
+import static org.openremote.model.asset.AssetType.CONSOLE;
+import static org.openremote.model.notification.PushNotificationMessage.TargetType.DEVICE;
+import static org.openremote.model.notification.PushNotificationMessage.TargetType.TOPIC;
+import static org.openremote.model.query.BaseAssetQuery.Include.ALL_EXCEPT_PATH;
+import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME;
+import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
+
+public class PushNotificationHandler extends RouteBuilder implements NotificationHandler {
+
+ private static final Logger LOG = Logger.getLogger(PushNotificationHandler.class.getName());
+ public static final String FIREBASE_CONFIG_FILE = "FIREBASE_CONFIG_FILE";
+ public static final int CONNECT_TIMEOUT_MILLIS = 3000;
+ public static final int READ_TIMEOUT_MILLIS = 3000;
+ public static final String FCM_PROVIDER_NAME = "fcm";
+
+ protected AssetStorageService assetStorageService;
+ protected boolean valid;
+ protected Map<String, String> consoleFCMTokenMap = new HashMap<>();
+ protected List<String> fcmTokenBlacklist = new ArrayList<>();
+ protected AbstractNotificationMessage lastSentMessage; // Bit of a hack to track topic based messages
+
+ public void init(Container container) throws Exception {
+ this.assetStorageService = container.getService(AssetStorageService.class);
+ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
+
+ String firebaseConfigFilePath = container.getConfig().get(FIREBASE_CONFIG_FILE);
+
+ if (TextUtil.isNullOrEmpty(firebaseConfigFilePath)) {
+ LOG.info(FIREBASE_CONFIG_FILE + " not defined, can not send FCM notifications");
+ return;
+ }
+
+ if (!Files.isReadable(Paths.get(firebaseConfigFilePath))) {
+ LOG.info(FIREBASE_CONFIG_FILE + " invalid path or file not readable");
+ return;
+ }
+
+ try (InputStream is = Files.newInputStream(Paths.get(firebaseConfigFilePath))) {
+ FirebaseOptions options = new FirebaseOptions.Builder()
+ .setCredentials(GoogleCredentials.fromStream(is))
+ .setConnectTimeout(CONNECT_TIMEOUT_MILLIS)
+ .setReadTimeout(READ_TIMEOUT_MILLIS)
+ .build();
+
+ FirebaseApp.initializeApp(options);
+ valid = true;
+ } catch (Exception ex) {
+ LOG.severe("Exception occurred whilst initialising FCM");
+ }
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+
+ if (!isValid()) {
+ return;
+ }
+
+ // Find all console assets that use this adapter
+ consoleFCMTokenMap = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
+ false,
+ AttributeType.CONSOLE_PROVIDERS.getName()))
+ .type(CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
+ new ObjectValueKeyPredicate("push")))
+ .stream()
+ .filter(PushNotificationHandler::isLinkedToFcmProvider)
+ .collect(Collectors.toMap(Asset::getId, asset -> getFcmToken(asset).orElse(null)));
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void configure() throws Exception {
+ // If any console asset was modified in the database, detect push provider changes
+ from(PERSISTENCE_TOPIC)
+ .routeId("PushNotificationAssetChanges")
+ .filter(isPersistenceEventForEntityType(Asset.class))
+ .process(exchange -> {
+ if (isPersistenceEventForAssetType(CONSOLE).matches(exchange)) {
+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
+ final Asset console = (Asset) persistenceEvent.getEntity();
+ processConsoleAssetChange(console, persistenceEvent);
+ }
+ });
+ }
+
+ @Override
+ public String getTypeName() {
+ return PushNotificationMessage.TYPE;
+ }
+
+ @Override
+ public boolean isMessageValid(AbstractNotificationMessage message) {
+ if (!isValid()) {
+ LOG.warning("Invalid message: FCM invalid configuration");
+ return false;
+ }
+
+ if (!(message instanceof PushNotificationMessage)) {
+ LOG.warning("Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of PushNotificationMessage");
+ return false;
+ }
+
+ PushNotificationMessage pushMessage = (PushNotificationMessage)message;
+ if (TextUtil.isNullOrEmpty(pushMessage.getTitle()) && pushMessage.getData() == null) {
+ LOG.warning("Invalid message: must either contain a title and/or data");
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public Notification.Targets mapTarget(Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+
+ // Check if message is going to a topic if so then filter consoles subscribed to that topic
+ PushNotificationMessage pushMessage = (PushNotificationMessage)message;
+ BaseAssetQuery.Select select = null;
+ boolean forTopic = pushMessage.getTargetType() == TOPIC;
+ List<Asset> mappedConsoles = null;
+
+ if (forTopic) {
+ select = new BaseAssetQuery.Select(ONLY_ID_AND_NAME_AND_ATTRIBUTES, false, AttributeType.CONSOLE_PROVIDERS.getName());
+ } else {
+ select = new BaseAssetQuery.Select(ONLY_ID_AND_NAME);
+ }
+
+ switch (targetType) {
+
+ case TENANT:
+ // Get all console assets with a push provider defined within the specified tenant
+ mappedConsoles = assetStorageService.findAll(
+ new AssetQuery()
+ .select(select)
+ .tenant(new TenantPredicate(targetId))
+ .type(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
+ );
+
+ if (forTopic) {
+ mappedConsoles.removeIf(c -> !isConsoleSubscribedToTopic(c, pushMessage.getTarget()));
+ }
+
+ if (mappedConsoles.isEmpty()) {
+ LOG.fine("No console assets linked to target realm");
+ return null;
+ }
+
+ return new Notification.Targets(Notification.TargetType.ASSET,
+ mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
+
+ case USER:
+
+ // Get all console assets linked to the specified user
+ List<String> ids = assetStorageService.findUserAssets(null, targetId, null)
+ .stream()
+ .map(userAsset -> userAsset.getId().getAssetId()).collect(Collectors.toList());
+
+ if (!ids.isEmpty()) {
+
+ mappedConsoles = assetStorageService.findAll(
+ new AssetQuery()
+ .select(select)
+ .ids(ids)
+ .type(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
+ );
+
+ if (forTopic) {
+ mappedConsoles.removeIf(c ->
+ !isConsoleSubscribedToTopic(c, pushMessage.getTarget())
+ );
+ }
+ } else {
+ LOG.fine("No console assets linked to target user");
+ return null;
+ }
+
+ return new Notification.Targets(Notification.TargetType.ASSET,
+ mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
+
+ case ASSET:
+
+ // Find all console descendants of the specified asset
+ mappedConsoles = assetStorageService.findAll(
+ new AssetQuery()
+ .select(select)
+ .path(new PathPredicate(targetId))
+ .type(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
+ );
+
+ if (forTopic) {
+ mappedConsoles.removeIf(c -> !isConsoleSubscribedToTopic(c, pushMessage.getTarget()));
+ }
+
+ if (mappedConsoles.isEmpty()) {
+ LOG.fine("No console assets descendants of target asset");
+ return null;
+ }
+
+ return new Notification.Targets(Notification.TargetType.ASSET,
+ mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
+ }
+
+ return null;
+ }
+
+ @Override
+ public NotificationSendResult sendMessage(long id, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+ if (targetType != Notification.TargetType.ASSET) {
+ LOG.warning("Target type not supported: " + targetType);
+ return NotificationSendResult.failure("Target type not supported: " + targetType);
+ }
+
+ if (!isValid()) {
+ LOG.warning("FCM invalid configuration so ignoring");
+ return NotificationSendResult.failure("FCM invalid configuration so ignoring");
+ }
+
+ String fcmToken = consoleFCMTokenMap.get(targetId);
+
+ if (TextUtil.isNullOrEmpty(fcmToken)) {
+ LOG.warning("No FCM token found for console: " + targetId);
+ return NotificationSendResult.failure("FCM invalid configuration so ignoring");
+ }
+
+ PushNotificationMessage pushMessage = (PushNotificationMessage)message;
+ if (pushMessage.getTargetType() == DEVICE) {
+ pushMessage.setTarget(targetId);
+ } else if (pushMessage.getTargetType() == TOPIC && pushMessage == lastSentMessage) {
+ LOG.info("Message is for topic and already sent so skipping send");
+ return NotificationSendResult.success();
+ }
+
+ lastSentMessage = pushMessage;
+ return sendMessage(buildFCMMessage(id, pushMessage));
+ }
+
+// public NotificationSendResult sendMessage(PushNotificationMessage.TargetType targetType, String fcmTarget, Message.Builder messageBuilder) {
+//
+// switch (targetType) {
+// case DEVICE:
+// messageBuilder.setToken(fcmTarget);
+// break;
+// case TOPIC:
+// messageBuilder.setTopic(fcmTarget);
+// break;
+// case CONDITION:
+// messageBuilder.setCondition(fcmTarget);
+// break;
+// }
+//
+// NotificationSendResult result = sendMessage(messageBuilder.build());
+// if (result.isSuccess()) {
+// LOG.warning("FCM send to '" + targetType + ":" + fcmTarget + "' success");
+// } else {
+// LOG.warning("FCM send to '" + targetType + ":" + fcmTarget + "' failed: " + result.getMessage());
+// }
+//
+// return result;
+// }
+
+ public boolean isValid() {
+ return valid;
+ }
+
+ protected boolean isConsoleSubscribedToTopic(Asset asset, String topic) {
+ return ConsoleConfiguration.getConsoleProvider(asset, PushNotificationMessage.TYPE)
+ .map(ConsoleProvider::getData)
+ .flatMap(objectValue -> objectValue.getArray("topics"))
+ .map(arrayValue -> arrayValue.contains(topic))
+ .orElse(false);
+ }
+
+ protected NotificationSendResult sendMessage(Message message) {
+ if (!isValid()) {
+ LOG.warning("FCM invalid configuration so ignoring");
+ return NotificationSendResult.failure("FCM invalid configuration so ignoring");
+ }
+
+ try {
+ FirebaseMessaging.getInstance().send(message);
+ return NotificationSendResult.success();
+ } catch (FirebaseMessagingException e) {
+ handleFcmException(e);
+ return NotificationSendResult.failure("FCM send failed: " + e.getErrorCode());
+ }
+ }
+
+ protected static Message buildFCMMessage(long id, PushNotificationMessage pushMessage) {
+
+ Message.Builder builder = Message.builder();
+ boolean dataOnly = TextUtil.isNullOrEmpty(pushMessage.getTitle());
+
+ switch (pushMessage.getTargetType()) {
+ case DEVICE:
+ builder.setToken(pushMessage.getTarget());
+ break;
+ case TOPIC:
+ builder.setTopic(pushMessage.getTarget());
+ break;
+ case CONDITION:
+ builder.setCondition(pushMessage.getTarget());
+ break;
+ }
+
+ AndroidConfig.Builder androidConfigBuilder = AndroidConfig.builder();
+ ApnsConfig.Builder apnsConfigBuilder = ApnsConfig.builder();
+ Aps.Builder apsBuilder = Aps.builder();
+ WebpushConfig.Builder webpushConfigBuilder = WebpushConfig.builder();
+
+ if (!dataOnly) {
+ // Don't set basic notification on Android if there is data so even if app is in background we can show a custom notification
+ // with actions that use the actions from the data
+ if (pushMessage.getData() != null || pushMessage.getAction() != null || pushMessage.getButtons() != null) {
+ androidConfigBuilder.putData("or-title", pushMessage.getTitle());
+ androidConfigBuilder.putData("or-body", pushMessage.getBody());
+ }
+
+ // Use alert dictionary for apns
+ // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html
+ apsBuilder.setAlert(ApsAlert.builder().setTitle(pushMessage.getTitle()).setBody(pushMessage.getBody()).build())
+ .setSound("default");
+
+ webpushConfigBuilder.setNotification(new WebpushNotification(pushMessage.getTitle(), pushMessage.getBody()));
+ }
+
+ if (pushMessage.getData() != null) {
+ pushMessage.getData().stream().forEach(stringValuePair -> {
+ if (stringValuePair.value != null) {
+ builder.putData(stringValuePair.key, stringValuePair.value.toJson());
+ }
+ });
+
+ if (dataOnly) {
+ apsBuilder.setContentAvailable(true);
+ }
+ }
+
+ // Store ID so console can mark notification as delivered and/or acknowledged
+ builder.putData("notification-id", Long.toString(id));
+
+ try {
+ if (pushMessage.getAction() != null) {
+ builder.putData("action", Container.JSON.writeValueAsString(pushMessage.getAction()));
+ }
+
+ if (pushMessage.getButtons() != null) {
+ builder.putData("buttons", Container.JSON.writeValueAsString(pushMessage.getButtons()));
+ }
+ } catch (JsonProcessingException e) {
+ e.printStackTrace();
+ }
+
+ androidConfigBuilder.setPriority(pushMessage.getPriority() == PushNotificationMessage.MessagePriority.HIGH ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL);
+ apnsConfigBuilder.putHeader("apns-priority", !dataOnly ? "10" : "5"); // Don't use 10 for data only
+
+ // set the following APNS flag to allow console to customise the notification before delivery and to ensure delivery
+ apsBuilder.setMutableContent(true);
+
+ if (pushMessage.getTtlSeconds() != null) {
+ long timeToLiveSeconds = Math.max(pushMessage.getTtlSeconds(), 0);
+ long timeToLiveMillis = timeToLiveSeconds * 1000;
+ Date expirationDate = new Date(new Date().getTime() + timeToLiveMillis);
+ long epochSeconds = Math.round(((float) expirationDate.getTime()) / 1000);
+
+ apnsConfigBuilder.putHeader("apns-expiration", Long.toString(epochSeconds));
+ androidConfigBuilder.setTtl(timeToLiveMillis);
+ webpushConfigBuilder.putHeader("TTL", Long.toString(timeToLiveSeconds));
+ }
+
+ apnsConfigBuilder.setAps(apsBuilder.build());
+ builder.setAndroidConfig(androidConfigBuilder.build());
+ builder.setApnsConfig(apnsConfigBuilder.build());
+ builder.setWebpushConfig(webpushConfigBuilder.build());
+
+ return builder.build();
+ }
+
+ protected static boolean isLinkedToFcmProvider(Asset asset) {
+ return ConsoleConfiguration.getConsoleProvider(asset, "geofence")
+ .map(ConsoleProvider::getVersion).map(FCM_PROVIDER_NAME::equals).orElse(false);
+ }
+
+ protected static Optional<String> getFcmToken(Asset asset) {
+ return ConsoleConfiguration.getConsoleProvider(asset, "push")
+ .map(ConsoleProvider::getData)
+ .flatMap(objValue -> objValue.getString("token"));
+ }
+
+ protected void processConsoleAssetChange(Asset asset, PersistenceEvent persistenceEvent) {
+
+ withLock(getClass().getSimpleName() + "::processAssetChange", () -> {
+
+ String fcmToken = consoleFCMTokenMap.remove(asset.getId());
+ if (!TextUtil.isNullOrEmpty(fcmToken)) {
+ fcmTokenBlacklist.remove(fcmToken);
+ }
+
+ switch (persistenceEvent.getCause()) {
+
+ case INSERT:
+ case UPDATE:
+
+ consoleFCMTokenMap.put(asset.getId(), getFcmToken(asset).orElse(null));
+ break;
+ }
+ });
+ }
+
+ protected void handleFcmException(FirebaseMessagingException e) {
+
+ LOG.log(Level.WARNING, "FCM send failed: " + e.getErrorCode(), e);
+
+ // TODO: Implement backoff and blacklisting
+ switch (e.getErrorCode()) {
+
+ case "invalid-argument":
+ case "authentication-error":
+ LOG.severe("FCM critical error so marking FCM as invalid no more messages will be sent");
+ break;
+ case "server-unavailable":
+ case "internal-error":
+
+ break;
+ }
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
index e4c881979..b5719242b 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -22,18 +22,20 @@ package org.openremote.manager.rules;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import org.geotools.referencing.GeodeticCalculator;
-import org.openremote.model.asset.BaseAssetQuery;
-import org.openremote.model.asset.BaseAssetQuery.*;
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.BaseAssetQuery.*;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.geo.GeoJSONPoint;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.*;
import org.openremote.model.rules.AssetState;
import java.util.Arrays;
import java.util.Locale;
import java.util.function.Predicate;
-import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_EQUALS;
-import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_THAN;
+import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_EQUALS;
+import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_THAN;
/**
* Test an {@link AssetState} with a {@link BaseAssetQuery}.
@@ -49,7 +51,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
@Override
public boolean test(AssetState assetState) {
- if (query.id != null && !query.id.equals(assetState.getId()))
+ if (query.ids != null && !query.ids.contains(assetState.getId()))
return false;
if (query.name != null && !asPredicate(query.name).test(assetState.getName()))
@@ -72,7 +74,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
return false;
if (query.attribute != null) {
- for (BaseAssetQuery.AttributePredicate p : query.attribute) {
+ for (AttributePredicate p : query.attribute) {
if (!asPredicate(p).test(assetState))
return false;
}
@@ -245,22 +247,22 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
if (predicate.value == null)
return true;
- if (predicate.value instanceof BaseAssetQuery.ValueEmptyPredicate) {
+ if (predicate.value instanceof ValueEmptyPredicate) {
return !assetState.getValue().isPresent();
- } else if (predicate.value instanceof BaseAssetQuery.ValueNotEmptyPredicate) {
+ } else if (predicate.value instanceof ValueNotEmptyPredicate) {
return assetState.getValue().isPresent();
- } else if (predicate.value instanceof BaseAssetQuery.StringPredicate) {
+ } else if (predicate.value instanceof StringPredicate) {
StringPredicate p = (StringPredicate) predicate.value;
return asPredicate(p).test(assetState.getValueAsString().orElse(null));
- } else if (predicate.value instanceof BaseAssetQuery.BooleanPredicate) {
+ } else if (predicate.value instanceof BooleanPredicate) {
BooleanPredicate p = (BooleanPredicate) predicate.value;
return asPredicate(p).test(assetState.getValueAsBoolean().orElse(null));
- } else if (predicate.value instanceof BaseAssetQuery.NumberPredicate) {
+ } else if (predicate.value instanceof NumberPredicate) {
NumberPredicate p = (NumberPredicate) predicate.value;
return asPredicate(p).test(assetState.getValueAsNumber().orElse(null));
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index e9f013c0d..034a78596 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -27,12 +27,12 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.concurrent.ManagerExecutorService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.facade.AssetsFacade;
-import org.openremote.manager.rules.facade.ConsolesFacade;
+import org.openremote.manager.rules.facade.NotificationsFacade;
import org.openremote.manager.rules.facade.UsersFacade;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.rules.*;
import java.util.*;
@@ -47,14 +47,14 @@ import static org.openremote.manager.rules.RulesetDeployment.Status.*;
public class RulesEngine<T extends Ruleset> {
/**
- * Identifies a set of {@link BaseAssetQuery.LocationPredicate}s associated with a particular {@link Asset}
+ * Identifies a set of {@link LocationPredicate}s associated with a particular {@link Asset}
*/
public static final class AssetStateLocationPredicates {
protected final String assetId;
- protected final Set<BaseAssetQuery.LocationPredicate> locationPredicates;
+ protected final Set<LocationPredicate> locationPredicates;
- public AssetStateLocationPredicates(String assetId, Set<BaseAssetQuery.LocationPredicate> locationPredicates) {
+ public AssetStateLocationPredicates(String assetId, Set<LocationPredicate> locationPredicates) {
this.assetId = assetId;
this.locationPredicates = locationPredicates;
}
@@ -63,7 +63,7 @@ public class RulesEngine<T extends Ruleset> {
return assetId;
}
- public Set<BaseAssetQuery.LocationPredicate> getLocationPredicates() {
+ public Set<LocationPredicate> getLocationPredicates() {
return locationPredicates;
}
}
@@ -83,7 +83,7 @@ public class RulesEngine<T extends Ruleset> {
final protected RulesEngineId<T> id;
final protected Assets assetsFacade;
final protected Users usersFacade;
- final protected ConsolesFacade consolesFacade;
+ final protected NotificationsFacade notificationFacade;
final protected AssetLocationPredicateProcessor assetLocationPredicatesConsumer;
final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();
@@ -116,7 +116,7 @@ public class RulesEngine<T extends Ruleset> {
AssetsFacade<T> assetsFacade = new AssetsFacade<>(id, assetStorageService, assetProcessingService::sendAttributeEvent);
this.assetsFacade = assetsFacade;
this.usersFacade = new UsersFacade<>(id, assetStorageService, notificationService, identityService);
- this.consolesFacade = new ConsolesFacade<>(assetsFacade, notificationService, identityService);
+ this.notificationFacade = new NotificationsFacade<>(id, notificationService);
this.assetLocationPredicatesConsumer = assetLocationPredicatesConsumer;
this.facts = new RulesFacts(assetsFacade, this, RULES_LOG);
@@ -207,7 +207,7 @@ public class RulesEngine<T extends Ruleset> {
deployment = new RulesetDeployment(ruleset.getId(), ruleset.getName(), ruleset.getVersion());
- boolean compilationSuccessful = deployment.registerRules(ruleset, assetsFacade, usersFacade, consolesFacade);
+ boolean compilationSuccessful = deployment.registerRules(ruleset, assetsFacade, usersFacade, notificationFacade);
if (!compilationSuccessful) {
// If any other ruleset is DEPLOYED in this scope, demote to READY
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
index 8ef542e63..b9e92a60c 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -22,10 +22,10 @@ package org.openremote.manager.rules;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
-import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.rules.AssetState;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.TemporaryFact;
@@ -66,7 +66,7 @@ public class RulesFacts extends Facts implements RuleListener {
protected int triggerCount;
protected boolean trackLocationRules;
- protected Map<String, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = null;
+ protected Map<String, Set<LocationPredicate>> assetStateLocationPredicateMap = null;
public RulesFacts(Assets assetsFacade, Object loggingContext, Logger logger) {
this.assetsFacade = assetsFacade;
@@ -87,7 +87,7 @@ public class RulesFacts extends Facts implements RuleListener {
protected List<RulesEngine.AssetStateLocationPredicates> stopTrackingLocationRules() {
LOG.finer("Tracking location predicate rules: stopping");
trackLocationRules = false;
- Map<String, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;
+ Map<String, Set<LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;
this.assetStateLocationPredicateMap = null;
return assetStateLocationPredicateMap.entrySet().stream()
.map(assetStateSetEntry ->
@@ -450,7 +450,7 @@ public class RulesFacts extends Facts implements RuleListener {
// If the query is by asset ID, look up a smaller stream on asset ID index
Collection<AssetState> assetStatesForId;
- if (assetQuery.id != null && ((assetStatesForId = assetIdIndex.get(assetQuery.id)) != null)) {
+ if (assetQuery.ids != null && ((assetStatesForId = assetIdIndex.get(assetQuery.ids)) != null)) {
return assetStatesForId.stream().parallel().filter(p);
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java
index d154bc55f..dd1b31ae9 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java
@@ -24,8 +24,8 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.asset.UserAsset;
import org.openremote.model.http.RequestParams;
import org.openremote.model.rules.AssetRuleset;
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 2451c217a..99adc57c0 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -36,6 +36,10 @@ import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent.Source;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.filter.AttributeMetaPredicate;
+import org.openremote.model.query.filter.BooleanPredicate;
+import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.rules.*;
import org.openremote.model.rules.geofence.GeofenceDefinition;
import org.openremote.model.security.Tenant;
@@ -735,9 +739,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new AssetQuery()
.select(new AssetQuery.Select(AssetQuery.Include.ALL))
.attributeMeta(
- new AssetQuery.AttributeMetaPredicate(
+ new AttributeMetaPredicate(
AssetMeta.RULE_STATE,
- new AssetQuery.BooleanPredicate(true))
+ new BooleanPredicate(true))
));
return assets.stream()
@@ -748,8 +752,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
/**
* Called when an engine's rules change identifying assets with location attributes marked with {@link
- * AssetMeta#RULE_STATE} that also have {@link BaseAssetQuery.LocationPredicate} in the rules. The job here is to
- * identify the asset's (via {@link AssetState}) that have modified {@link BaseAssetQuery.LocationPredicate}s and to
+ * AssetMeta#RULE_STATE} that also have {@link LocationPredicate} in the rules. The job here is to
+ * identify the asset's (via {@link AssetState}) that have modified {@link LocationPredicate}s and to
* notify the {@link GeofenceAssetAdapter}s.
*/
protected void onEngineLocationRulesChanged(RulesEngine rulesEngine, List<RulesEngine.AssetStateLocationPredicates> newEngineAssetStateLocationPredicates) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index acc16e821..ce611eeb1 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -31,7 +31,7 @@ import org.jeasy.rules.api.Rules;
import org.jeasy.rules.core.RuleBuilder;
import org.kohsuke.groovy.sandbox.GroovyValueFilter;
import org.kohsuke.groovy.sandbox.SandboxTransformer;
-import org.openremote.manager.rules.facade.ConsolesFacade;
+import org.openremote.manager.rules.facade.NotificationsFacade;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Ruleset;
import org.openremote.model.rules.Users;
@@ -160,18 +160,18 @@ public class RulesetDeployment {
return rules;
}
- public boolean registerRules(Ruleset ruleset, Assets assetsFacade, Users usersFacade, ConsolesFacade consolesFacade) {
+ public boolean registerRules(Ruleset ruleset, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationFacade) {
RulesEngine.LOG.info("Evaluating ruleset deployment: " + ruleset);
switch (ruleset.getLang()) {
case JAVASCRIPT:
- return registerRulesJavascript(ruleset, assetsFacade, usersFacade, consolesFacade);
+ return registerRulesJavascript(ruleset, assetsFacade, usersFacade, notificationFacade);
case GROOVY:
- return registerRulesGroovy(ruleset, assetsFacade, usersFacade, consolesFacade);
+ return registerRulesGroovy(ruleset, assetsFacade, usersFacade, notificationFacade);
}
return false;
}
- public boolean registerRulesJavascript(Ruleset ruleset, Assets assetsFacade, Users usersFacade, ConsolesFacade consolesFacade) {
+ public boolean registerRulesJavascript(Ruleset ruleset, Assets assetsFacade, Users usersFacade, NotificationsFacade consolesFacade) {
// TODO https://github.com/pfisterer/scripting-sandbox/blob/master/src/main/java/de/farberg/scripting/sandbox/ScriptingSandbox.java
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
ScriptContext newContext = new SimpleScriptContext();
@@ -192,20 +192,21 @@ public class RulesetDeployment {
" \"org.openremote.model.asset\",\n" +
" \"org.openremote.model.attribute\",\n" +
" \"org.openremote.model.value\",\n" +
- " \"org.openremote.model.rules\"\n" +
+ " \"org.openremote.model.rules\",\n" +
+ " \"org.openremote.model.query\"\n" +
");\n" +
- "var Match = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Match\");\n" +
- "var Operator = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Operator\");\n" +
- "var NumberType = Java.type(\"org.openremote.model.asset.BaseAssetQuery$NumberType\");\n" +
- "var StringPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$StringPredicate\");\n" +
- "var BooleanPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$BooleanPredicate\");\n" +
- "var StringArrayPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$StringArrayPredicate\");\n" +
- "var DateTimePredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$DateTimePredicate\");\n" +
- "var NumberPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$NumberPredicate\");\n" +
- "var ParentPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$ParentPredicate\");\n" +
- "var PathPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$PathPredicate\");\n" +
- "var TenantPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$TenantPredicate\");\n" +
- "var AttributePredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$AttributePredicate\");\n" +
+ "var Match = Java.type(\"org.openremote.model.query.BaseAssetQuery$Match\");\n" +
+ "var Operator = Java.type(\"org.openremote.model.query.BaseAssetQuery$Operator\");\n" +
+ "var NumberType = Java.type(\"org.openremote.model.query.BaseAssetQuery$NumberType\");\n" +
+ "var StringPredicate = Java.type(\"org.openremote.model.query.filter.StringPredicate\");\n" +
+ "var BooleanPredicate = Java.type(\"org.openremote.model.query.filter.BooleanPredicate\");\n" +
+ "var StringArrayPredicate = Java.type(\"org.openremote.model.query.filter.StringArrayPredicate\");\n" +
+ "var DateTimePredicate = Java.type(\"org.openremote.model.query.filter.DateTimePredicate\");\n" +
+ "var NumberPredicate = Java.type(\"org.openremote.model.query.filter.NumberPredicate\");\n" +
+ "var ParentPredicate = Java.type(\"org.openremote.model.query.filter.ParentPredicate\");\n" +
+ "var PathPredicate = Java.type(\"org.openremote.model.query.filter.PathPredicate\");\n" +
+ "var TenantPredicate = Java.type(\"org.openremote.model.query.filter.TenantPredicate\");\n" +
+ "var AttributePredicate = Java.type(\"org.openremote.model.query.filter.AttributePredicate\");\n" +
"var AttributeExecuteStatus = Java.type(\"org.openremote.model.attribute.AttributeExecuteStatus\");\n" +
"var EXACT = Match.EXACT;\n" +
"var BEGIN = Match.BEGIN;\n" +
@@ -314,7 +315,7 @@ public class RulesetDeployment {
}
}
- public boolean registerRulesGroovy(Ruleset ruleset, Assets assetsFacade, Users usersFacade, ConsolesFacade consolesFacade) {
+ public boolean registerRulesGroovy(Ruleset ruleset, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationFacade) {
try {
// TODO Implement sandbox
// new DenyAll().register();
@@ -325,7 +326,7 @@ public class RulesetDeployment {
binding.setVariable("rules", rulesBuilder);
binding.setVariable("assets", assetsFacade);
binding.setVariable("users", usersFacade);
- binding.setVariable("consoles", consolesFacade);
+ binding.setVariable("notifications", notificationFacade);
script.setBinding(binding);
script.run();
for (Rule rule : rulesBuilder.build()) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
index 706533c9b..3a55e73be 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
@@ -22,13 +22,16 @@ package org.openremote.manager.rules.facade;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.rules.RulesEngineId;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.rules.*;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
+import java.util.Collections;
import java.util.function.Consumer;
import java.util.stream.Stream;
@@ -86,12 +89,15 @@ public class AssetsFacade<T extends Ruleset> extends Assets {
@Override
public String getResult() {
+ // TODO: 'Security' checks must be done here as AssetQuery fields can easily be set by a rule
Asset asset = assetStorageService.find(this);
return asset != null ? asset.getId() : null;
}
@Override
public Stream<String> stream() {
+ // TODO: 'Security' checks must be done here as AssetQuery fields can easily be set by a rule
+
if (this.select == null)
this.select = new Select();
Include oldValue = this.select.include;
@@ -127,7 +133,7 @@ public class AssetsFacade<T extends Ruleset> extends Assets {
// Check if the asset ID of the event can be found with the default query of this facade
BaseAssetQuery<RestrictedQuery> checkQuery = query();
- checkQuery.id = event.getEntityId(); // Set directly on field, as modifying query restrictions is not allowed
+ checkQuery.ids = Collections.singletonList(event.getEntityId()); // Set directly on field, as modifying query restrictions is not allowed
if (assetStorageService.find(checkQuery) == null) {
throw new IllegalArgumentException(
"Access to asset not allowed for this rule engine scope: " + event
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/ConsolesFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/ConsolesFacade.java
deleted file mode 100644
index 329de3781..000000000
--- a/manager/src/main/java/org/openremote/manager/rules/facade/ConsolesFacade.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.rules.facade;
-
-import org.openremote.manager.notification.NotificationService;
-import org.openremote.manager.security.ManagerIdentityService;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetType;
-import org.openremote.model.asset.BaseAssetQuery;
-import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.rules.Assets;
-import org.openremote.model.rules.Ruleset;
-
-public class ConsolesFacade<T extends Ruleset> {
-
- protected final AssetsFacade<T> assetsFacade;
- protected final NotificationService notificationService;
- protected final ManagerIdentityService identityService;
-
- public ConsolesFacade(AssetsFacade<T> assetsFacade, NotificationService notificationService, ManagerIdentityService identityService) {
- this.assetsFacade = assetsFacade;
- this.notificationService = notificationService;
- this.identityService = identityService;
- }
-
- public void notify(String consoleId, AlertNotification alert) {
-
- // Check if the console asset can be found with the default query of this facade
- BaseAssetQuery<Assets.RestrictedQuery> checkQuery = assetsFacade.query();
- checkQuery.id = consoleId; // Set directly on field, as modifying query restrictions is not allowed
- Asset console = assetsFacade.assetStorageService.find(checkQuery);
- if (console == null || console.getWellKnownType() != AssetType.CONSOLE) {
- throw new IllegalArgumentException(
- "Access to console not allowed for this rule engine scope: " + consoleId
- );
- }
-
- notificationService.notifyConsole(consoleId, alert);
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java
new file mode 100644
index 000000000..b7846484e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.rules.facade;
+
+import org.openremote.manager.notification.NotificationService;
+import org.openremote.manager.rules.RulesEngineId;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.rules.GlobalRuleset;
+import org.openremote.model.rules.Notifications;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.rules.TenantRuleset;
+
+import java.util.function.Consumer;
+
+import static org.openremote.model.notification.Notification.Source.ASSET_RULESET;
+import static org.openremote.model.notification.Notification.Source.GLOBAL_RULESET;
+import static org.openremote.model.notification.Notification.Source.TENANT_RULESET;
+
+public class NotificationsFacade<T extends Ruleset> extends Notifications {
+
+ protected final RulesEngineId<T> rulesEngineId;
+ protected final NotificationService notificationService;
+
+ public NotificationsFacade(RulesEngineId<T> rulesEngineId, NotificationService notificationService) {
+ this.rulesEngineId = rulesEngineId;
+ this.notificationService = notificationService;
+ }
+
+ public void send(Notification notification) {
+ Notification.Source source;
+ String sourceId = null;
+
+ if (rulesEngineId.getScope() == GlobalRuleset.class) {
+ source = GLOBAL_RULESET;
+ } else if (rulesEngineId.getScope() == TenantRuleset.class) {
+ source = TENANT_RULESET;
+ sourceId = rulesEngineId.getRealmId().orElseThrow(() -> new IllegalStateException("Tenant ruleset must have a realm ID"));
+ } else {
+ source = ASSET_RULESET;
+ sourceId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ruleset must have an asset ID"));
+ }
+
+ notificationService.sendNotification(notification, source, sourceId);
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
index dbffb6051..2c1b8f9bb 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
@@ -23,13 +23,16 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.RulesEngineId;
import org.openremote.manager.security.ManagerIdentityService;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
+import org.openremote.model.query.filter.UserAssetPredicate;
import org.openremote.model.rules.*;
-import org.openremote.model.user.UserQuery;
+import org.openremote.model.security.User;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
-import java.util.function.Consumer;
+import java.util.stream.Collectors;
/**
* Restricts rule RHS access to the scope of the engine (a rule in asset scope can not access users in global scope).
@@ -43,57 +46,56 @@ public class UsersFacade<T extends Ruleset> extends Users {
public class UsersResctrictedQueryFacade extends Users.RestrictedQuery {
- public UsersResctrictedQueryFacade() {
- if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- tenantPredicate = new UserQuery.TenantPredicate(
- rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
- );
- }
- if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId));
- Asset restrictedAsset = assetStorageService.find(assetId, true);
- if (restrictedAsset == null) {
- // An asset was deleted in the database, but its ruleset is still deployed. This
- // can happen while the PersistenceEvent of the deletion is not processed and the
- // rules engine fires. This exception marks the ruleset deployment as execution
- // error status, and as soon as the PersistenceEvent is processed, the ruleset
- // deployment is removed and the problem resolved.
- throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
- }
- assetPredicate = new UserQuery.AssetPredicate(assetId);
- }
- }
-
@Override
- public Users.RestrictedQuery tenant(UserQuery.TenantPredicate tenantPredicate) {
+ public Users.RestrictedQuery tenant(TenantPredicate tenantPredicate) {
if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
return super.tenant(tenantPredicate);
throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
}
@Override
- public Users.RestrictedQuery asset(UserQuery.AssetPredicate assetPredicate) {
- if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
- return super.asset(assetPredicate);
+ public List<String> getResults() {
+ // Do security checks to ensure correct scoping
+ // No restriction for global rulesets
if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- return super.asset(assetPredicate);
- // TODO: should only be allowed if asset belongs to tenant
- }
- if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- return super.asset(assetPredicate);
- // TODO: should only be allowed if restricted asset is descendant of scope's asset
- }
- throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
- }
+ if (tenantPredicate != null) {
+ throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
+ }
- @Override
- public List<String> getResults() {
- return notificationService.findAllUsersWithToken(this);
- }
+ // Restrict tenant
+ tenantPredicate = new TenantPredicate(
+ rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
+ );
+ } else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
+ if (tenantPredicate != null) {
+ throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
+ }
+ String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalArgumentException("Asset ID missing: " + rulesEngineId));
- @Override
- public void applyResults(Consumer<List<String>> usersIdListConsumer) {
- usersIdListConsumer.accept(getResults());
+ // Asset must be this engines asset or a child
+ if (assetPredicate != null) {
+ if (assetId.equals(assetPredicate.id)) {
+ pathPredicate = null;
+ } else {
+ pathPredicate = new PathPredicate(new String[]{rulesEngineId.getAssetId().orElseThrow(
+ IllegalArgumentException::new)});
+ }
+ } else if (pathPredicate != null) {
+ // Path must contain this engines asset ID
+ List<String> path = new ArrayList<>(Arrays.asList(pathPredicate.path));
+ if (!path.contains(assetId)) {
+ path.add(assetId);
+ pathPredicate.path = path.toArray(new String[pathPredicate.path.length + 1]);
+ }
+ } else {
+ // Force scope to this asset
+ assetPredicate = new UserAssetPredicate(assetId);
+ }
+ }
+
+ return Arrays.stream(identityService.getIdentityProvider().getUsers(this))
+ .map(User::getId)
+ .collect(Collectors.toList());
}
}
@@ -108,28 +110,4 @@ public class UsersFacade<T extends Ruleset> extends Users {
public Users.RestrictedQuery query() {
return new UsersResctrictedQueryFacade();
}
-
- @Override
- public void storeAndNotify(String userId, AlertNotification alert) {
- if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- boolean userIsInTenant = identityService.getIdentityProvider().isUserInTenant(
- userId,
- rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
- );
- if (!userIsInTenant) {
- throw new IllegalArgumentException("User not in tenant " + rulesEngineId + ": " + userId);
- }
- }
- if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- boolean userIsLinkedToAsset = assetStorageService.isUserAsset(
- userId,
- rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId))
- );
- if (!userIsLinkedToAsset) {
- throw new IllegalArgumentException("User not linked to asset " + rulesEngineId + ": " + userId);
- }
- }
- notificationService.storeAndNotify(userId, alert);
- }
-
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java
index 8f0cfe3e6..e9557f298 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java
@@ -21,14 +21,14 @@ package org.openremote.manager.rules.geofence;
import org.openremote.manager.rules.RulesEngine;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.rules.geofence.GeofenceDefinition;
import java.util.List;
/**
- * Defines an adapter that can take a collection of {@link BaseAssetQuery.LocationPredicate} that apply to a given
- * {@link Asset} and can convert the {@link BaseAssetQuery.LocationPredicate}s into Geofences that can be implemented by
+ * Defines an adapter that can take a collection of {@link LocationPredicate} that apply to a given
+ * {@link Asset} and can convert the {@link LocationPredicate}s into Geofences that can be implemented by
* the asset(s) itself.
* <p>
* The adapter is notified when the {@link Asset}s {@link RulesEngine.AssetStateLocationPredicates} change; if the
@@ -61,7 +61,7 @@ public interface GeofenceAssetAdapter {
/**
* The initialising flag is used to indicate that the system is just initialising and the adapter is being made
- * aware of existing {@link BaseAssetQuery.LocationPredicate}s; generally adapters should use this to initialise
+ * aware of existing {@link LocationPredicate}s; generally adapters should use this to initialise
* their own state rather than 'pushing' geofences to the asset(s) it can be assumed that they were previously sent,
* hence adapters should be more concerned with delta changes (but this is really up to the adapter).
* <p>
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index 0c497fdcc..122bc5418 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -30,13 +30,21 @@ import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.RulesEngine;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.console.ConsoleConfiguration;
import org.openremote.model.console.ConsoleProvider;
+import org.openremote.model.notification.Notification;
+import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.query.filter.LocationPredicate;
+import org.openremote.model.query.filter.ObjectValueKeyPredicate;
+import org.openremote.model.query.filter.RadialLocationPredicate;
import org.openremote.model.rules.geofence.GeofenceDefinition;
import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
@@ -46,6 +54,8 @@ import java.util.stream.Collectors;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.container.persistence.PersistenceEvent.*;
+import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD;
+import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl;
import static org.openremote.model.asset.AssetType.CONSOLE;
/**
@@ -60,8 +70,6 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
private static final Logger LOG = Logger.getLogger(ORConsoleGeofenceAssetAdapter.class.getName());
public static final String NAME = "ORConsole";
- public static final String HTTP_METHOD = "PUT";
- public static final String LOCATION_URL_FORMAT_TEMPLATE = "/asset/%1$s/attribute/location";
public static int NOTIFY_ASSETS_DEBOUNCE_MILLIS = 60000;
protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();
protected NotificationService notificationService;
@@ -92,7 +100,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
AttributeType.CONSOLE_PROVIDERS.getName()))
.type(CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
- new BaseAssetQuery.ObjectValueKeyPredicate("geofence")))
+ new ObjectValueKeyPredicate("geofence")))
.stream()
.filter(ORConsoleGeofenceAssetAdapter::isLinkedToORConsoleGeofenceAdapter)
.collect(Collectors.toMap(Asset::getId, Asset::getTenantRealm));
@@ -149,7 +157,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
assetStateLocationPredicates
.getLocationPredicates()
.removeIf(locationPredicate ->
- !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));
+ !(locationPredicate instanceof RadialLocationPredicate));
// If not initialising compare existing with new predicates and notify affected assets
if (!initialising) {
@@ -213,23 +221,29 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
.toArray(GeofenceDefinition[]::new);
}
- protected GeofenceDefinition locationPredicateToGeofenceDefinition(String assetId, BaseAssetQuery.LocationPredicate locationPredicate) {
- BaseAssetQuery.RadialLocationPredicate radialLocationPredicate = (BaseAssetQuery.RadialLocationPredicate) locationPredicate;
+ protected GeofenceDefinition locationPredicateToGeofenceDefinition(String assetId, LocationPredicate locationPredicate) {
+ RadialLocationPredicate radialLocationPredicate = (RadialLocationPredicate) locationPredicate;
String id = assetId + "_" + Integer.toString(radialLocationPredicate.hashCode());
- String url = String.format(LOCATION_URL_FORMAT_TEMPLATE,
- assetId);
+ String url = getWriteAttributeUrl(new AttributeRef(assetId, AttributeType.LOCATION.getName()));
return new GeofenceDefinition(id,
radialLocationPredicate.getLat(),
radialLocationPredicate.getLng(),
radialLocationPredicate.getRadius(),
- HTTP_METHOD,
+ WRITE_ATTRIBUTE_HTTP_METHOD,
url);
}
+ /**
+ * Send a silent push notification to the console to get it to refresh its geofences
+ */
protected void notifyAssetGeofencesChanged(String assetId) {
- Map<String, String> data = new HashMap<>();
+ ObjectValue data = Values.createObject();
data.put("action", "GEOFENCE_REFRESH");
- notificationService.notifyConsoleSilently(assetId, data);
+ notificationService.sendNotification(
+ new Notification(
+ "GeofenceRefresh",
+ new PushNotificationMessage().setData(data),
+ new Notification.Targets(Notification.TargetType.ASSET, Collections.singletonList(assetId))));
}
protected void processConsoleAssetChange(Asset asset, PersistenceEvent persistenceEvent) {
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
index 03f8af468..b739f9fef 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
@@ -27,8 +27,10 @@ import org.openremote.manager.persistence.ManagerPersistenceService;
import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.event.shared.TenantFilter;
+import org.openremote.model.query.UserQuery;
import org.openremote.model.security.*;
+import java.util.List;
import java.util.Objects;
import java.util.Set;
@@ -50,6 +52,16 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
return new User[0];
}
+ @Override
+ public User[] getUsers(List<String> userIds) {
+ return new User[0];
+ }
+
+ @Override
+ public User[] getUsers(UserQuery userQuery) {
+ return new User[0];
+ }
+
@Override
public User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {
return null;
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index d3250d94b..3532a3f71 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -24,8 +24,11 @@ import org.openremote.container.security.IdentityProvider;
import org.openremote.container.web.ClientRequestInfo;
import org.openremote.model.asset.Asset;
import org.openremote.model.event.shared.TenantFilter;
+import org.openremote.model.query.UserQuery;
import org.openremote.model.security.*;
+import java.util.List;
+
/**
* SPI for implementations used by {@link ManagerIdentityService}, provides CRUD of
* {@link User} and {@link Tenant}.
@@ -34,6 +37,10 @@ public interface ManagerIdentityProvider extends IdentityProvider {
User[] getUsers(ClientRequestInfo clientRequestInfo, String realm);
+ User[] getUsers(List<String> userIds);
+
+ User[] getUsers(UserQuery userQuery);
+
User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId);
User getUser(String realm, String userName);
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index e4d984ef7..ffa657f92 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -39,14 +39,20 @@ import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetTreeModifiedEvent;
import org.openremote.model.event.shared.TenantFilter;
+import org.openremote.model.query.UserQuery;
import org.openremote.model.security.*;
+import org.openremote.model.util.TextUtil;
+import javax.persistence.Query;
+import javax.persistence.TypedQuery;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
+import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
+import java.util.stream.IntStream;
import static org.openremote.container.util.JsonUtil.convert;
import static org.openremote.model.Constants.*;
@@ -101,6 +107,84 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
return users.toArray(new User[users.size()]);
}
+ @Override
+ public User[] getUsers(List<String> userIds) {
+ return persistenceService.doReturningTransaction(em -> {
+ List<User> result =
+ em.createQuery("select u from User u where u.id IN :userIds", User.class)
+ .setParameter("userIds", userIds)
+ .getResultList();
+
+ return result.toArray(new User[result.size()]);
+ });
+ }
+
+ @Override
+ public User[] getUsers(UserQuery userQuery) {
+
+ LOG.fine("Building: " + userQuery);
+ StringBuilder sb = new StringBuilder();
+ List<Object> parameters = new ArrayList<>();
+ sb.append(buildSelectString(userQuery));
+ sb.append(buildFromString(userQuery));
+ sb.append(buildWhereString(userQuery, parameters));
+
+ return persistenceService.doReturningTransaction(entityManager -> {
+ TypedQuery<User> query = entityManager.createQuery(sb.toString(), User.class);
+ IntStream.range(0, parameters.size()).forEach(i -> query.setParameter(i+1, parameters.get(i)));
+ List<User> users = query.getResultList();
+ return users.toArray(new User[users.size()]);
+ });
+ }
+
+
+ protected String buildSelectString(UserQuery query) {
+ return "SELECT DISTINCT(u)";
+ }
+
+ protected String buildFromString(UserQuery query) {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append(" FROM User u");
+
+ if (query.assetPredicate != null || query.pathPredicate != null) {
+ sb.append(" join UserAsset ua on ua.id.userId = u.id");
+ }
+
+ if (query.tenantPredicate != null && TextUtil.isNullOrEmpty(query.tenantPredicate.realm)) {
+ sb.append(" join PUBLIC.REALM R on R.ID = u.realmId");
+ }
+
+ return sb.toString();
+ }
+
+ protected String buildWhereString(UserQuery query, List<Object> parameters) {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append(" WHERE 1=1");
+
+ if (query.tenantPredicate != null) {
+ if (!TextUtil.isNullOrEmpty(query.tenantPredicate.realmId)) {
+ sb.append(" AND u.realmId = ?").append(parameters.size() + 1);
+ parameters.add(query.tenantPredicate.realmId);
+ } else if (!TextUtil.isNullOrEmpty(query.tenantPredicate.realm)) {
+ sb.append(" AND r.name = ?").append(parameters.size() + 1);
+ parameters.add(query.tenantPredicate.realm);
+ }
+
+ }
+ if (query.assetPredicate != null) {
+ sb.append(" AND ua.id.assetId = ?").append(parameters.size() + 1);
+ parameters.add(query.assetPredicate.id);
+ }
+ if (query.pathPredicate != null) {
+ sb.append(" AND ?").append(parameters.size() + 1).append(" <@ get_asset_tree_path(ua.asset_id)");
+ parameters.add(query.pathPredicate.path);
+ }
+
+ return sb.toString();
+ }
+
@Override
public User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {
return convertUser(
diff --git a/manager/src/main/resources/META-INF/persistence.xml b/manager/src/main/resources/META-INF/persistence.xml
index f53731747..4473bc8f4 100644
--- a/manager/src/main/resources/META-INF/persistence.xml
+++ b/manager/src/main/resources/META-INF/persistence.xml
@@ -12,8 +12,7 @@
<class>org.openremote.model.asset.Asset</class>
<class>org.openremote.model.notification.DeviceNotificationToken</class>
- <class>org.openremote.model.notification.AlertNotification</class>
- <class>org.openremote.model.notification.AlertAction</class>
+ <class>org.openremote.model.notification.SentNotification</class>
<class>org.openremote.manager.security.UserConfiguration</class>
<class>org.openremote.model.datapoint.AssetDatapoint</class>
<class>org.openremote.model.asset.UserAsset</class>
diff --git a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
index f0029464d..089c22294 100644
--- a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
@@ -1,20 +1,23 @@
package demo.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.manager.rules.facade.ConsolesFacade
+import org.openremote.manager.rules.facade.NotificationsFacade
import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.notification.Notification
+import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
-import org.openremote.model.asset.BaseAssetQuery
import org.openremote.model.attribute.AttributeType
-import org.openremote.model.notification.AlertNotification
+import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.query.filter.RadialLocationPredicate
+import org.openremote.model.query.filter.ValueEmptyPredicate
import org.openremote.model.rules.Assets
+import org.openremote.model.rules.Notifications
import java.util.logging.Logger
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
-ConsolesFacade consolesFacade = binding.consoles
+Notifications notifications = binding.notifications
Assets assets = binding.assets
rules.add()
@@ -25,7 +28,7 @@ rules.add()
def consoleIds = facts.matchAssetState(new AssetQuery()
.type(AssetType.CONSOLE)
.location(
- new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x)))
+ new RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x)))
.filter({!facts.getOptional("welcomeHome" + "_${it.id}").isPresent()})
.map({it.id})
.collect()
@@ -41,15 +44,15 @@ rules.add()
facts ->
List<String> consoleIds = facts.bound("consoleIds")
+ Notification notification = new Notification(
+ "Welcome Home",
+ new PushNotificationMessage("Welcome Home", "No new events to report", null, null, null),
+ new Notification.Targets(Notification.TargetType.ASSET, consoleIds))
- AlertNotification alert = new AlertNotification(
- title: "Welcome Home",
- message: "No new events to report"
- )
+ notifications.send(notification)
consoleIds.forEach({
LOG.info("Welcome Home triggered: $it")
- consolesFacade.notify(it, alert)
facts.put("welcomeHome" + "_${it}", it)
})
})
@@ -61,7 +64,7 @@ rules.add()
def consoleIds = facts.matchAssetState(new AssetQuery()
.type(AssetType.CONSOLE)
- .attributeValue(AttributeType.LOCATION.name, new BaseAssetQuery.ValueEmptyPredicate()))
+ .attributeValue(AttributeType.LOCATION.name, new ValueEmptyPredicate()))
.filter({facts.getOptional("welcomeHome" + "_${it.id}").isPresent()})
.map({it.id})
.collect()
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
index 6a8648bf4..827644e9c 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
@@ -2,8 +2,8 @@ package demo.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.rules.RulesFacts
-import org.openremote.model.asset.AssetQuery
-import org.openremote.model.asset.BaseAssetQuery.Operator
+import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.BaseAssetQuery.Operator
import org.openremote.model.rules.AssetState
import java.util.logging.Logger
@@ -11,7 +11,7 @@ import java.util.stream.Stream
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.asset.BaseAssetQuery.Operator.*
+import static org.openremote.model.query.BaseAssetQuery.Operator.*
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
index 862422aef..d0d82a305 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
@@ -2,10 +2,15 @@ package demo.rules
import groovy.transform.ToString
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
-import org.openremote.model.notification.AlertNotification
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.PushNotificationAction
+import org.openremote.model.notification.PushNotificationButton
+import org.openremote.model.query.AssetQuery
+import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.query.filter.UserAssetPredicate
+import org.openremote.model.rules.Notifications
import org.openremote.model.rules.Users
-import org.openremote.model.user.UserQuery
import org.openremote.model.value.Values
import java.util.logging.Logger
@@ -16,6 +21,7 @@ import static org.openremote.model.asset.AssetType.ROOM
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
Users users = binding.users
+Notifications notifications = binding.notifications
@ToString(includeNames = true)
class AlarmTrigger {
@@ -142,23 +148,28 @@ rules.add()
{ facts ->
AlarmTrigger alarmTrigger = facts.bound("alarmTrigger")
- AlertNotification alert = new AlertNotification(
- title: "Apartment Alarm",
- message: "Aanwezigheid in " + alarmTrigger.roomName + " (" + facts.clock.time + ")."
- )
- alert.addLinkAction("Details", "#security")
- alert.addActuatorAction("Alarm uit", alarmTrigger.residenceId, "alarmEnabled", Values.create(false).toJson())
-
- // This only includes users which have a device notification token (registered console device)!
+ // Get users linked to this residence
List<String> userIds = users
.query()
- .asset(new UserQuery.AssetPredicate(alarmTrigger.residenceId))
+ .asset(new UserAssetPredicate(alarmTrigger.residenceId))
.getResults()
LOG.info("Alerting users of " + alarmTrigger + ": " + userIds)
- userIds.forEach({ userId ->
- users.storeAndNotify(userId, alert)
- })
+
+ Notification notification = new Notification(
+ "ApartmentAlarm",
+ new PushNotificationMessage()
+ .setTitle("Apartment Alarm")
+ .setBody("Aanwezigheid in " + alarmTrigger.roomName + " (" + facts.clock.time + ").")
+ .setButtons([
+ new PushNotificationButton("Details", new PushNotificationAction("#security")),
+ new PushNotificationButton("Alarm uit", PushNotificationAction.writeAttributeValueAction(new AttributeRef(alarmTrigger.residenceId, "alarmEnabled"), Values.create(false)))
+ ]),
+ new Notification.Targets(Notification.TargetType.USER, userIds)
+ )
+
+ // Send the notification to all matched users
+ notifications.send(notification)
AlertSilence alertSilence = new AlertSilence(
residenceName: alarmTrigger.residenceName,
diff --git a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
index cbbb4864f..db487e18b 100644
--- a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
@@ -10,7 +10,7 @@ assets have presence set.
package demo.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.rules.AssetState
import org.openremote.model.util.Pair
@@ -18,8 +18,8 @@ import java.util.logging.Logger
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.asset.BaseAssetQuery.Operator.GREATER_THAN
-import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_THAN
+import static org.openremote.model.query.BaseAssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_THAN
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy b/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
index 965e09ce3..c9abb751e 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
@@ -2,7 +2,7 @@ package demo.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.rules.RulesFacts
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.rules.AssetState
import org.openremote.model.value.Values
@@ -13,7 +13,7 @@ import java.util.logging.Logger
import java.util.stream.Stream
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.asset.BaseAssetQuery.Match.BEGIN
+import static org.openremote.model.query.BaseAssetQuery.Match.BEGIN
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
index a7cf4fd20..25e24c639 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
@@ -2,15 +2,15 @@ package demo.rules
import groovy.transform.ToString
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.rules.AssetState
import org.openremote.model.rules.Assets
import java.util.logging.Logger
import static org.openremote.model.asset.AssetType.RESIDENCE
-import static org.openremote.model.asset.BaseAssetQuery.Operator.GREATER_THAN
-import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_EQUALS
+import static org.openremote.model.query.BaseAssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_EQUALS
import static org.openremote.model.attribute.AttributeExecuteStatus.REQUEST_START
Logger LOG = binding.LOG
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql
new file mode 100644
index 000000000..3856dfc71
--- /dev/null
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql
@@ -0,0 +1,24 @@
+
+/*
+ New notification infrastructure, rather than migrate existing notifications the entire table is dropped and recreated
+ */
+
+drop table ALERT_NOTIFICATION cascade;
+drop table DEVICE_NOTIFICATION_TOKEN cascade;
+
+create table NOTIFICATION (
+ ID int8 not null,
+ NAME varchar(255) not null,
+ TYPE varchar(50) not null,
+ TARGET varchar(50) not null,
+ TARGET_ID varchar(43) not null,
+ SOURCE varchar(50) not null,
+ SOURCE_ID varchar(43),
+ MESSAGE jsonb,
+ ERROR varchar(255),
+ SENT_ON timestamp with time zone not null,
+ DELIVERED_ON timestamp with time zone,
+ ACKNOWLEDGED_ON timestamp with time zone,
+ ACKNOWLEDGEMENT varchar(255),
+ primary key (ID)
+);
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/AbstractTypeHolder.java b/model/src/main/java/org/openremote/model/AbstractTypeHolder.java
deleted file mode 100644
index 0abd9448f..000000000
--- a/model/src/main/java/org/openremote/model/AbstractTypeHolder.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model;
-
-import org.openremote.model.value.ObjectValue;
-import org.openremote.model.value.Values;
-
-import java.util.Objects;
-import java.util.Optional;
-
-/**
- * Base class for all model classes which have to internally store data in an
- * {@link ObjectValue} that has a <code>type</code> field that accepts a string.
- */
-public abstract class AbstractTypeHolder {
-
- protected static final String TYPE_FIELD_NAME = "type";
-
- final protected ObjectValue objectValue;
-
- public AbstractTypeHolder() {
- this(Values.createObject());
- }
-
- public AbstractTypeHolder(String type) {
- this(Values.createObject(), type);
- }
-
- public AbstractTypeHolder(ObjectValue objectValue) {
- Objects.requireNonNull(objectValue);
- this.objectValue = objectValue;
- }
-
- public AbstractTypeHolder(ObjectValue objectValue, String type) {
- Objects.requireNonNull(objectValue);
- this.objectValue = objectValue;
- setType(type);
- }
-
- public ObjectValue getObjectValue() {
- return objectValue;
- }
-
- public void setType(String type) {
- objectValue.put(TYPE_FIELD_NAME, type);
- }
-
- public Optional<String> getType() {
- return objectValue.getString(TYPE_FIELD_NAME);
- }
-
- @Override
- public String toString() {
- return objectValue.toJson();
- }
-}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java
index 592f535ce..ff40bcac9 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java
@@ -20,11 +20,10 @@
package org.openremote.model.asset;
import jsinterop.annotations.JsType;
-import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.geo.GeoJSONPoint;
+import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.http.RequestParams;
import org.openremote.model.http.SuccessStatusCode;
-import org.openremote.model.value.ValueType;
+import org.openremote.model.query.AssetQuery;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
@@ -62,6 +61,14 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@JsType(isNative = true)
public interface AssetResource {
+ class Util {
+ public static final String WRITE_ATTRIBUTE_HTTP_METHOD = "PUT";
+
+ public static String getWriteAttributeUrl(AttributeRef attributeRef) {
+ return "/asset/" + attributeRef.getEntityId() + "/attribute/" + attributeRef.getAttributeName();
+ }
+ }
+
// TODO This returns the same as #queryAssets, can it be removed?
/**
diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java
deleted file mode 100644
index 2fbc5517a..000000000
--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java
+++ /dev/null
@@ -1,1305 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.asset;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.annotation.JsonSubTypes;
-import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.MetaItemDescriptor;
-import org.openremote.model.value.*;
-
-import java.util.Arrays;
-import java.util.Locale;
-import java.util.Objects;
-
-/**
- * Encapsulate asset query restriction, projection, and ordering of results.
- */
-// TODO: Add AssetQuery support for arbitrary attribute property path amd value (e.g. attributes.consoleProviders.geofence.version == "ORConsole")
-@SuppressWarnings("unchecked")
-public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
-
- public enum Include {
- ALL_EXCEPT_PATH_AND_ATTRIBUTES,
- ALL_EXCEPT_PATH,
- ONLY_ID_AND_NAME,
- ONLY_ID_AND_NAME_AND_ATTRIBUTES,
- ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES,
- ALL
- }
-
- public enum Access {
- PRIVATE_READ,
- RESTRICTED_READ,
- PUBLIC_READ
- }
-
- /**
- * String matching options
- */
- public enum Match {
- EXACT,
- NOT_EXACT,
- BEGIN,
- END,
- CONTAINS;
-
- public String prepare(String string) {
- if (string == null)
- return null;
- switch (this) {
- case BEGIN:
- return string + "%";
- case CONTAINS:
- return "%" + string + "%";
- case END:
- return "%" + string;
- }
- return string;
- }
- }
-
- /**
- * Binary operators
- */
- public enum Operator {
- EQUALS,
- NOT_EQUALS,
- GREATER_THAN,
- GREATER_EQUALS,
- LESS_THAN,
- LESS_EQUALS,
- BETWEEN
- }
-
- public enum NumberType {
- DOUBLE,
- INTEGER
- }
-
- @JsonSubTypes({
- @JsonSubTypes.Type(value = StringPredicate.class, name = "string"),
- @JsonSubTypes.Type(value = BooleanPredicate.class, name = "boolean"),
- @JsonSubTypes.Type(value = StringArrayPredicate.class, name = "string-array"),
- @JsonSubTypes.Type(value = DateTimePredicate.class, name = "datetime"),
- @JsonSubTypes.Type(value = NumberPredicate.class, name = "number")
- })
- @JsonTypeInfo(
- use = JsonTypeInfo.Id.NAME,
- include = JsonTypeInfo.As.PROPERTY,
- property = "predicateType"
- )
- public interface ValuePredicate<T> {
-
- ObjectValue toModelValue();
- }
-
- public static class Select {
-
- public Include include;
- public boolean recursive;
- public Access access;
- public String[] attributeNames;
-
- public Select() {
- }
-
- public Select(Include include) {
- this(include, Access.PRIVATE_READ);
- }
-
- public Select(Include include, Access access) {
- this(include, false, access);
- }
-
- public Select(Include include, boolean recursive, Access access) {
- this(include, recursive, access, (String[]) null);
- }
-
- public Select(Include include, boolean recursive, String... attributeNames) {
- this(include, recursive, Access.PRIVATE_READ, attributeNames);
- }
-
- public Select(Include include, boolean recursive, Access access, String... attributeNames) {
- if (include == null) {
- include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
- }
- this.include = include;
- this.access = access;
- this.recursive = recursive;
- this.attributeNames = attributeNames;
- }
-
- public static Select fromObjectValue(ObjectValue objectValue) {
- Select select = new Select();
- objectValue.getString("include").ifPresent(include -> {
- select.include = Include.valueOf(include);
- });
- objectValue.getString("access").ifPresent(access -> {
- select.access = Access.valueOf(access);
- });
- objectValue.getBoolean("recursive").ifPresent(recursive -> {
- select.recursive = recursive;
- });
- objectValue.getArray("attributeNames").ifPresent(attributeNames -> {
- select.attributeNames = attributeNames.stream()
- .map(value -> (StringValue) value)
- .map(StringValue::getString)
- .toArray(String[]::new);
- });
- return select;
- }
-
- public Select include(Include include) {
- this.include = include;
- return this;
- }
-
- public Select filterAccess(Access access) {
- this.access = access;
- return this;
- }
-
- public Select filterAttributes(String... attributeNames) {
- this.attributeNames = attributeNames;
- return this;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("include", Values.create(include.toString()));
- objectValue.put("recursive", Values.create(recursive));
- objectValue.put("access", Values.create(access.toString()));
- objectValue.put("attributeNames",
- Values.createArray().addAll(Arrays.stream(attributeNames).map(Values::create).toArray(Value[]::new)));
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "include=" + include +
- ", recursive=" + recursive +
- ", access=" + access +
- ", attributeNames=" + Arrays.toString(attributeNames) +
- '}';
- }
- }
-
- public static class ValueEmptyPredicate implements ValuePredicate<Value> {
-
- @Override
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "ValueEmptyPredicate");
- return objectValue;
- }
- }
-
- public static class ValueNotEmptyPredicate implements ValuePredicate<Value> {
-
- @Override
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "ValueNotEmptyPredicate");
- return objectValue;
- }
- }
-
- public static class StringPredicate implements ValuePredicate<String> {
-
- public Match match = Match.EXACT;
- public boolean caseSensitive = true;
- public String value;
-
- public StringPredicate() {
- }
-
- public StringPredicate(String value) {
- this.value = value;
- }
-
- public StringPredicate(Match match, String value) {
- this.match = match;
- this.value = value;
- }
-
- public StringPredicate(Match match, boolean caseSensitive, String value) {
- this.match = match;
- this.caseSensitive = caseSensitive;
- this.value = value;
- }
-
- public static StringPredicate fromObjectValue(ObjectValue objectValue) {
- StringPredicate stringPredicate = new StringPredicate();
- objectValue.getString("match").ifPresent(match -> {
- stringPredicate.match = Match.valueOf(match);
- });
- objectValue.getBoolean("caseSensitive").ifPresent(caseSensitive -> {
- stringPredicate.caseSensitive = caseSensitive;
- });
- objectValue.getString("value").ifPresent(value -> {
- stringPredicate.value = value;
- });
- return stringPredicate;
- }
-
- public StringPredicate match(Match match) {
- this.match = match;
- return this;
- }
-
- public StringPredicate caseSensitive(boolean caseSensitive) {
- this.caseSensitive = caseSensitive;
- return this;
- }
-
- public StringPredicate value(String value) {
- this.value = value;
- return this;
- }
-
- public String prepareValue() {
- String s = match.prepare(this.value);
- if (!caseSensitive)
- s = s.toUpperCase(Locale.ROOT);
- return s;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "StringPredicate");
- objectValue.put("match", Values.create(match.toString()));
- objectValue.put("caseSensitive", Values.create(caseSensitive));
- objectValue.put("value", Values.create(value));
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "match=" + match +
- ", caseSensitive=" + caseSensitive +
- ", value='" + value + '\'' +
- '}';
- }
- }
-
- public static class BooleanPredicate implements ValuePredicate<Boolean> {
-
- public boolean value;
-
- public BooleanPredicate() {
- }
-
- public BooleanPredicate(boolean value) {
- this.value = value;
- }
-
- public static BooleanPredicate fromObjectValue(ObjectValue objectValue) {
- BooleanPredicate booleanPredicate = new BooleanPredicate();
- booleanPredicate.value = objectValue
- .getBoolean("value")
- .orElseThrow(() -> new IllegalArgumentException("value missing for BooleanPredicate"));
- return booleanPredicate;
- }
-
- public BooleanPredicate value(boolean value) {
- this.value = value;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "predicate=" + value +
- '}';
- }
-
- @Override
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "BooleanPredicate");
- objectValue.put("value", Values.create(value));
- return objectValue;
- }
- }
-
- public static class StringArrayPredicate implements ValuePredicate<String[]> {
-
- public StringPredicate[] predicates = new StringPredicate[0];
-
- public StringArrayPredicate() {
- }
-
- public StringArrayPredicate(StringPredicate... predicates) {
- this.predicates = predicates;
- }
-
- public static StringArrayPredicate fromObjectValue(ObjectValue objectValue) {
- StringArrayPredicate stringArrayPredicate = new StringArrayPredicate();
- objectValue.getArray("value").ifPresent(arrayValue -> {
- ;
- stringArrayPredicate.predicates = objectValue.stream()
- .map(val -> (ObjectValue) val)
- .map(StringPredicate::fromObjectValue)
- .toArray(StringPredicate[]::new);
- });
- return stringArrayPredicate;
- }
-
- public StringArrayPredicate predicates(StringPredicate... predicates) {
- this.predicates = predicates;
- return this;
- }
-
- @Override
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "StringArrayPredicate");
- ArrayValue valuesArray = Values.createArray();
- for (StringPredicate stringPredicate : predicates) {
- valuesArray.add(stringPredicate.toModelValue());
- }
- objectValue.put("value", valuesArray);
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "predicates=" + Arrays.toString(predicates) +
- '}';
- }
- }
-
- public static class DateTimePredicate implements ValuePredicate<Long> {
-
- public String value;
- public String rangeValue; // Used as upper bound when Operator.BETWEEN
- public Operator operator = Operator.EQUALS;
- public String dateFormat = "YYYY-MM-DD HH24:MI:SS";//postgres dateformat
-
- public DateTimePredicate() {
- }
-
- public DateTimePredicate(Operator operator, String value) {
- this.operator = operator;
- this.value = value;
- }
-
- public DateTimePredicate(String rangeStart, String rangeEnd) {
- this.operator = Operator.BETWEEN;
- this.value = rangeStart;
- this.rangeValue = rangeEnd;
- }
-
- public static DateTimePredicate fromObjectValue(ObjectValue objectValue) {
- DateTimePredicate dateTimePredicate = new DateTimePredicate();
-
- objectValue.getString("dateFormat").ifPresent(format -> {
- dateTimePredicate.dateFormat = format;
- });
- objectValue.getString("value").ifPresent(value -> {
- dateTimePredicate.value = value;
- });
- objectValue.getString("rangeValue").ifPresent(rangeValue -> {
- dateTimePredicate.rangeValue = rangeValue;
- });
- objectValue.getString("operator").ifPresent(operator -> {
- dateTimePredicate.operator = Operator.valueOf(operator);
- });
- return dateTimePredicate;
- }
-
- public DateTimePredicate operator(Operator dateMatch) {
- this.operator = dateMatch;
- return this;
- }
-
- public DateTimePredicate dateFormat(String dateFormat) {
- this.dateFormat = dateFormat;
- return this;
- }
-
- public DateTimePredicate value(String value) {
- this.value = value;
- return this;
- }
-
- public DateTimePredicate rangeValue(String rangeEnd) {
- this.operator = Operator.BETWEEN;
- this.rangeValue = rangeEnd;
- return this;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "StringPredicate");
- objectValue.put("dateFormat", Values.create(dateFormat));
- objectValue.put("value", Values.create(value));
- objectValue.put("rangeValue", Values.create(rangeValue));
- objectValue.put("operator", Values.create(operator.toString()));
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "value='" + value + '\'' +
- ", rangeValue='" + rangeValue + '\'' +
- ", operator =" + operator +
- ", dateFormat='" + dateFormat + '\'' +
- '}';
- }
- }
-
- public static class NumberPredicate implements ValuePredicate<Double> {
-
- public double value;
- public double rangeValue; // Used as upper bound when Operator.BETWEEN
- public Operator operator = Operator.EQUALS;
- public NumberType numberType = NumberType.DOUBLE;
-
- public NumberPredicate() {
- }
-
- public NumberPredicate(double value) {
- this.value = value;
- }
-
- public NumberPredicate(double value, Operator operator) {
- this.value = value;
- this.operator = operator;
- }
-
- public NumberPredicate(double value, NumberType numberType) {
- this.value = value;
- this.numberType = numberType;
- }
-
- public NumberPredicate(double value, Operator operator, NumberType numberType) {
- this.value = value;
- this.operator = operator;
- this.numberType = numberType;
- }
-
- public static NumberPredicate fromObjectValue(ObjectValue objectValue) {
- NumberPredicate numberPredicate = new NumberPredicate();
- objectValue.getNumber("value").ifPresent(value -> {
- numberPredicate.value = value;
- });
- objectValue.getNumber("rangeValue").ifPresent(rangeValue -> {
- numberPredicate.rangeValue = rangeValue;
- });
- objectValue.getString("operator").ifPresent(operator -> {
- numberPredicate.operator = Operator.valueOf(operator);
- });
- return numberPredicate;
- }
-
- public NumberPredicate predicate(double predicate) {
- this.value = predicate;
- return this;
- }
-
- public NumberPredicate numberMatch(Operator operator) {
- this.operator = operator;
- return this;
- }
-
- public NumberPredicate numberType(NumberType numberType) {
- this.numberType = numberType;
- return this;
- }
-
- public NumberPredicate rangeValue(double rangeValue) {
- this.operator = Operator.BETWEEN;
- this.rangeValue = rangeValue;
- return this;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "StringPredicate");
- objectValue.put("value", Values.create(value));
- objectValue.put("rangeValue", Values.create(rangeValue));
- objectValue.put("operator", Values.create(operator.toString()));
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "value=" + value +
- ", rangeValue=" + rangeValue +
- ", operator=" + operator +
- ", numberType=" + numberType +
- '}';
- }
- }
-
- public static class ObjectValueKeyPredicate implements ValuePredicate<String> {
-
- public boolean negated;
- public String key;
-
- public ObjectValueKeyPredicate(String hasKey) {
- key = hasKey;
- }
-
- public ObjectValueKeyPredicate(String hasKey, boolean negate) {
- key = hasKey;
- negated = negate;
- }
-
- public ObjectValueKeyPredicate negate() {
- negated = !negated;
- return this;
- }
-
- @Override
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("predicateType", "ObjectValueKeyPredicate");
- objectValue.put("negated", Values.create(negated));
- objectValue.put("key", Values.create(key));
- return objectValue;
- }
- }
-
- public static class ParentPredicate {
-
- public String id;
- public String type;
- public boolean noParent;
-
- public ParentPredicate() {
- }
-
- public ParentPredicate(String id) {
- this.id = id;
- }
-
- public ParentPredicate(boolean noParent) {
- this.noParent = noParent;
- }
-
- public ParentPredicate id(String id) {
- this.id = id;
- return this;
- }
-
- public ParentPredicate type(String type) {
- this.type = type;
- return this;
- }
-
- public ParentPredicate type(AssetType type) {
- return type(type.getValue());
- }
-
- public ParentPredicate noParent(boolean noParent) {
- this.noParent = noParent;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "id='" + id + '\'' +
- ", type='" + type + '\'' +
- ", noParent=" + noParent +
- '}';
- }
- }
-
- public static class PathPredicate {
-
- public String[] path;
-
- public PathPredicate() {
- }
-
- public PathPredicate(String[] path) {
- this.path = path;
- }
-
- public PathPredicate path(String[] path) {
- this.path = path;
- return this;
- }
-
- public boolean hasPath() {
- return path != null && path.length > 0;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "path=" + Arrays.toString(path) +
- '}';
- }
- }
-
- public static class TenantPredicate {
-
- public String realmId;
- public String realm;
-
- public TenantPredicate() {
- }
-
- public TenantPredicate(String realmId) {
- this.realmId = realmId;
- }
-
- public TenantPredicate realmId(String id) {
- this.realmId = id;
- return this;
- }
-
- public TenantPredicate realm(String name) {
- this.realm = name;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "realmId='" + realmId + '\'' +
- ", realm='" + realm + '\'' +
- '}';
- }
- }
-
- public static class AttributePredicate {
-
- public StringPredicate name;
- public ValuePredicate value;
-
- public AttributePredicate() {
- }
-
- public AttributePredicate(String name) {
- this(new StringPredicate(name));
- }
-
- public AttributePredicate(StringPredicate name) {
- this.name = name;
- }
-
- public AttributePredicate(ValuePredicate value) {
- this.value = value;
- }
-
- public AttributePredicate(StringPredicate name, ValuePredicate value) {
- this.name = name;
- this.value = value;
- }
-
- public AttributePredicate name(StringPredicate name) {
- this.name = name;
- return this;
- }
-
- public AttributePredicate value(ValuePredicate value) {
- this.value = value;
- return this;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("name", name.toModelValue());
- objectValue.put("value", value.toModelValue());
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "name=" + name +
- ", value=" + value +
- '}';
- }
- }
-
- public static class AttributeMetaPredicate {
-
- public StringPredicate itemNamePredicate;
- public ValuePredicate itemValuePredicate;
-
- public AttributeMetaPredicate() {
- }
-
- public AttributeMetaPredicate(StringPredicate itemNamePredicate) {
- this.itemNamePredicate = itemNamePredicate;
- }
-
- public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor) {
- this.itemNamePredicate = new StringPredicate(metaItemDescriptor.getUrn());
- }
-
- public AttributeMetaPredicate(ValuePredicate itemValuePredicate) {
- this.itemValuePredicate = itemValuePredicate;
- }
-
- public AttributeMetaPredicate(StringPredicate itemNamePredicate, ValuePredicate itemValuePredicate) {
- this.itemNamePredicate = itemNamePredicate;
- this.itemValuePredicate = itemValuePredicate;
- }
-
- public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor, ValuePredicate itemValuePredicate) {
- this(new StringPredicate(metaItemDescriptor.getUrn()), itemValuePredicate);
- }
-
- public AttributeMetaPredicate itemName(StringPredicate itemNamePredicate) {
- this.itemNamePredicate = itemNamePredicate;
- return this;
- }
-
- public AttributeMetaPredicate itemName(MetaItemDescriptor metaItemDescriptor) {
- return itemName(new StringPredicate(metaItemDescriptor.getUrn()));
- }
-
- public AttributeMetaPredicate itemValue(ValuePredicate itemValuePredicate) {
- this.itemValuePredicate = itemValuePredicate;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "itemNamePredicate=" + itemNamePredicate +
- ", itemValuePredicate=" + itemValuePredicate +
- '}';
- }
- }
-
- public static class AttributeRefPredicate extends AttributeMetaPredicate {
-
- public AttributeRefPredicate() {
- }
-
- public AttributeRefPredicate(AttributeRef attributeRef) {
- this(attributeRef.getEntityId(), attributeRef.getAttributeName());
- }
-
- public AttributeRefPredicate(String entityId, String attributeName) {
- super(
- new StringArrayPredicate(
- new StringPredicate(entityId),
- new StringPredicate(attributeName)
- ));
- }
-
- public AttributeRefPredicate(String name, String entityId, String attributeName) {
- super(
- new StringPredicate(name),
- new StringArrayPredicate(
- new StringPredicate(entityId),
- new StringPredicate(attributeName)
- ));
- }
-
- public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, String entityId, String attributeName) {
- this(metaItemDescriptor.getUrn(), entityId, attributeName);
- }
-
- public AttributeRefPredicate(StringPredicate name, AttributeRef attributeRef) {
- super(
- name,
- new StringArrayPredicate(
- new StringPredicate(attributeRef.getEntityId()),
- new StringPredicate(attributeRef.getAttributeName())
- ));
- }
-
- public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, AttributeRef attributeRef) {
- this(new StringPredicate(metaItemDescriptor.getUrn()), attributeRef);
- }
- }
-
- public static class CalendarEventActivePredicate {
-
- @JsonProperty("timestamp")
- public long timestampSeconds;
-
- @JsonCreator
- public CalendarEventActivePredicate(@JsonProperty("timestamp") long timestampSeconds) {
- this.timestampSeconds = timestampSeconds;
- }
- }
-
- @JsonSubTypes({
- @JsonSubTypes.Type(value = RadialLocationPredicate.class, name = RadialLocationPredicate.name),
- @JsonSubTypes.Type(value = RectangularLocationPredicate.class, name = RectangularLocationPredicate.name)
- })
- @JsonTypeInfo(
- use = JsonTypeInfo.Id.NAME,
- include = JsonTypeInfo.As.PROPERTY,
- property = "predicateType"
- )
-
- public abstract static class LocationPredicate {
-
- // TODO: switch return type to location object
- public abstract double[] getCentrePoint();
- }
-
- public static class RadialLocationPredicate extends LocationPredicate {
-
- public static final String name = "radial";
- public boolean negated;
- public int radius;
- public double lat;
- public double lng;
-
- @JsonCreator
- public RadialLocationPredicate(@JsonProperty("radius") int radius,
- @JsonProperty("lat") double lat,
- @JsonProperty("lng") double lng,
- @JsonProperty("negated") boolean negated) {
- this.radius = radius;
- this.lat = lat;
- this.lng = lng;
- this.negated = negated;
- }
-
- public RadialLocationPredicate(@JsonProperty("radius") int radius,
- @JsonProperty("lat") double lat,
- @JsonProperty("lng") double lng) {
- this(radius, lat, lng, false);
- }
-
- public RadialLocationPredicate negate() {
- negated = true;
- return this;
- }
-
- public int getRadius() {
- return radius;
- }
-
- public double getLat() {
- return lat;
- }
-
- public double getLng() {
- return lng;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- RadialLocationPredicate that = (RadialLocationPredicate) o;
- return negated == that.negated &&
- radius == that.radius &&
- Double.compare(that.lat, lat) == 0 &&
- Double.compare(that.lng, lng) == 0;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name, negated, radius, lat, lng);
- }
-
- @Override
- public double[] getCentrePoint() {
- return new double[]{lng, lat};
- }
- }
-
- public static class RectangularLocationPredicate extends LocationPredicate {
-
- public static final String name = "rect";
- public boolean negated;
- public double latMin;
- public double lngMin;
- public double latMax;
- public double lngMax;
-
- @JsonCreator
- public RectangularLocationPredicate(@JsonProperty("latMin") double latMin,
- @JsonProperty("lngMin") double lngMin,
- @JsonProperty("latMax") double latMax,
- @JsonProperty("lngMax") double lngMax,
- @JsonProperty("negated") boolean negated) {
- this.latMin = latMin;
- this.lngMin = lngMin;
- this.latMax = latMax;
- this.lngMax = lngMax;
- this.negated = negated;
- }
-
- public RectangularLocationPredicate(@JsonProperty("latMin") double latMin,
- @JsonProperty("lngMin") double lngMin,
- @JsonProperty("latMax") double latMax,
- @JsonProperty("lngMax") double lngMax) {
- this(latMin, lngMin, latMax, lngMax, false);
- }
-
- public RectangularLocationPredicate negate() {
- negated = true;
- return this;
- }
-
- public double getLatMin() {
- return latMin;
- }
-
- public double getLngMin() {
- return lngMin;
- }
-
- public double getLatMax() {
- return latMax;
- }
-
- public double getLngMax() {
- return lngMax;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- RectangularLocationPredicate that = (RectangularLocationPredicate) o;
- return negated == that.negated &&
- Double.compare(that.latMin, latMin) == 0 &&
- Double.compare(that.lngMin, lngMin) == 0 &&
- Double.compare(that.latMax, latMax) == 0 &&
- Double.compare(that.lngMax, lngMax) == 0;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name, negated, latMin, lngMin, latMax, lngMax);
- }
-
- @Override
- public double[] getCentrePoint() {
- double x = (lngMin + lngMax) / 2;
- double y = (latMin + latMax) / 2;
- return new double[]{x, y};
- }
- }
-
- public static class OrderBy {
-
- public enum Property {
- CREATED_ON,
- NAME,
- ASSET_TYPE,
- PARENT_ID,
- REALM_ID
- }
-
- public Property property;
- public boolean descending;
-
- public OrderBy() {
- }
-
- public OrderBy(Property property) {
- this.property = property;
- }
-
- public OrderBy(Property property, boolean descending) {
- this.property = property;
- this.descending = descending;
- }
-
- public OrderBy property(Property property) {
- this.property = property;
- return this;
- }
-
- public OrderBy descending(boolean descending) {
- this.descending = descending;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "property=" + property +
- ", descending=" + descending +
- '}';
- }
- }
- // Projection
- public Select select;
- // Restriction predicates
- public String id;
- public StringPredicate name;
- public ParentPredicate parent;
- public PathPredicate path;
- public TenantPredicate tenant;
- public String userId;
- public StringPredicate type;
- public AttributePredicate[] attribute;
- public AttributeMetaPredicate[] attributeMeta;
- public CalendarEventActivePredicate calendarEventActive;
- public LocationPredicate location;
- // Ordering
- public OrderBy orderBy;
- protected BaseAssetQuery() {
- }
-
- public static final ArrayValue queriesAsValue(BaseAssetQuery... queries) {
- ArrayValue arrayValue = Values.createArray();
-
- for (BaseAssetQuery query : queries) {
- ObjectValue objectValue = Values.createObject();
- if (query.select != null) {
- objectValue.put("select", query.select.toModelValue());
- }
- if (query.type != null) {
- objectValue.put("type", query.type.toModelValue());
- }
- if (query.attribute != null && query.attribute.length > 0) {
- ArrayValue attributeArray = Values.createArray();
- for (AttributePredicate attributePredicate : query.attribute) {
- attributeArray.add(attributePredicate.toModelValue());
- }
- objectValue.put("attribute", attributeArray);
- }
- arrayValue.add(objectValue);
- }
- return arrayValue;
- }
-
- public static final AssetQuery objectValueAsQuery(ObjectValue objectValue) {
- AssetQuery assetQuery = new AssetQuery();
-
- objectValue.getObject("select").ifPresent(selectValue -> {
- assetQuery.select = Select.fromObjectValue(selectValue);
- });
-
- objectValue.getObject("type").ifPresent(typeValue -> {
- assetQuery.type = StringPredicate.fromObjectValue(typeValue);
- });
-
- objectValue.getArray("attribute").ifPresent(attributeValue -> {
- assetQuery.attribute = attributeValue.stream()
- .map(val -> (ObjectValue) val)
- .map(attributePredicateValue -> {
- AttributePredicate attributePredicate = new AttributePredicate();
-
- attributePredicate.name = StringPredicate.fromObjectValue(attributePredicateValue
- .getObject("name")
- .orElseThrow(() -> new IllegalArgumentException(
- "StringPredicate missing for name in AttributePredicate"))
- );
-
- ObjectValue predicateValue = attributePredicateValue
- .getObject("value")
- .orElseThrow(() -> new IllegalArgumentException("value missing in AttributePredicate"));
-
- predicateValue.getString("predicateType").ifPresent(predicateType -> {
- switch (predicateType) {
- case "StringPredicate":
- attributePredicate.value = StringPredicate.fromObjectValue(predicateValue);
- break;
- case "BooleanPredicate":
- attributePredicate.value = BooleanPredicate.fromObjectValue(predicateValue);
- break;
- case "StringArrayPredicate":
- attributePredicate.value = StringArrayPredicate.fromObjectValue(predicateValue);
- break;
- case "DateTimePredicate":
- attributePredicate.value = DateTimePredicate.fromObjectValue(predicateValue);
- break;
- case "NumberPredicate":
- attributePredicate.value = NumberPredicate.fromObjectValue(predicateValue);
- break;
- }
- });
- return attributePredicate;
- })
- .toArray(AttributePredicate[]::new);
- });
-
- return assetQuery;
- }
-
- public CHILD select(Select select) {
- if (select == null) {
- select = new Select();
- }
-
- this.select = select;
- return (CHILD) this;
- }
-
- public CHILD id(String id) {
- this.id = id;
- return (CHILD) this;
- }
-
- public CHILD name(String name) {
- return name(new StringPredicate(name));
- }
-
- public CHILD name(StringPredicate name) {
- this.name = name;
- return (CHILD) this;
- }
-
- public CHILD parent(String id) {
- return parent(new ParentPredicate(id));
- }
-
- public CHILD parent(AssetType assetType) {
- return parent(new ParentPredicate().type(assetType));
- }
-
- public CHILD parent(ParentPredicate parentPredicate) {
- this.parent = parentPredicate;
- return (CHILD) this;
- }
-
- public CHILD path(PathPredicate pathPredicate) {
- this.path = pathPredicate;
- return (CHILD) this;
- }
-
- public CHILD tenant(TenantPredicate tenantPredicate) {
- this.tenant = tenantPredicate;
- return (CHILD) this;
- }
-
- public CHILD userId(String userId) {
- this.userId = userId;
- return (CHILD) this;
- }
-
- public CHILD type(StringPredicate type) {
- this.type = type;
- return (CHILD) this;
- }
-
- public CHILD type(String type) {
- return type(new StringPredicate(type));
- }
-
- public CHILD type(AssetType assetType) {
- return type(new StringPredicate(assetType.getValue()));
- }
-
- public CHILD attributes(AttributePredicate... attributePredicates) {
- this.attribute = attributePredicates;
- return (CHILD) this;
- }
-
- public CHILD attributeName(String attributeName) {
- return attributes(new AttributePredicate(attributeName));
- }
-
- public CHILD attributeName(Match match, String attributeName) {
- return attributes(new AttributePredicate(new StringPredicate(match, attributeName)));
- }
-
- /**
- * Match non-empty attribute value.
- */
- public CHILD attributeValue(String name) {
- return attributes(new AttributePredicate(new StringPredicate(name), new ValueNotEmptyPredicate()));
- }
-
- public CHILD attributeValue(String name, ValuePredicate valuePredicate) {
- return attributes(new AttributePredicate(new StringPredicate(name), valuePredicate));
- }
-
- public CHILD attributeValue(String name, boolean b) {
- return attributeValue(name, new BooleanPredicate(b));
- }
-
- public CHILD attributeValue(String name, String s) {
- return attributeValue(name, new StringPredicate(s));
- }
-
- public CHILD attributeValue(String name, Match match, String s) {
- return attributeValue(name, new StringPredicate(match, s));
- }
-
- public CHILD attributeValue(String name, Match match, boolean caseSensitive, String s) {
- return attributeValue(name, new StringPredicate(match, caseSensitive, s));
- }
-
- public CHILD attributeValue(String name, double d) {
- return attributeValue(name, new NumberPredicate(d));
- }
-
- public CHILD attributeValue(String name, Operator operator, double d) {
- return attributeValue(name, new NumberPredicate(d, operator));
- }
-
- public CHILD attributeMeta(AttributeMetaPredicate... attributeMetaPredicates) {
- this.attributeMeta = attributeMetaPredicates;
- return (CHILD) this;
- }
-
- public CHILD orderBy(OrderBy orderBy) {
- this.orderBy = orderBy;
- return (CHILD) this;
- }
-
- /**
- * Will filter out assets that have a {@link CalendarEventConfiguration} attribute that results in the event not
- * being 'active/in progress' at the specified time. Assets without a {@link CalendarEventConfiguration} attribute
- * are assumed to always be in progress (i.e. will always pass this check).
- *
- * <b>
- * NOTE: This predicate is applied in memory and the results should be limited as much as possible by applying other
- * predicates to the query to avoid performance issues.
- * </b>
- */
- public CHILD calendarEventActive(long timestampSeconds) {
- calendarEventActive = new CalendarEventActivePredicate(timestampSeconds);
- return (CHILD) this;
- }
-
- public CHILD location(LocationPredicate locationPredicate) {
- this.location = locationPredicate;
- return (CHILD) this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "select=" + select +
- ", id='" + id + '\'' +
- ", name=" + name +
- ", parent=" + parent +
- ", path=" + path +
- ", tenant=" + tenant +
- ", userId='" + userId + '\'' +
- ", type=" + type +
- ", attribute=" + Arrays.toString(attribute) +
- ", attributeMeta=" + Arrays.toString(attributeMeta) +
- ", orderBy=" + orderBy +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
index 901e9edb6..e3070ec69 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
@@ -22,7 +22,6 @@ package org.openremote.model.geo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
-import org.openremote.model.AbstractTypeHolder;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
diff --git a/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java
new file mode 100644
index 000000000..6aaf547dd
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/AbstractNotificationMessage.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.openremote.model.value.ObjectValue;
+
+@JsonSubTypes(
+ @JsonSubTypes.Type(value = PushNotificationMessage.class, name = PushNotificationMessage.TYPE)
+)
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ property = "type"
+)
+public abstract class AbstractNotificationMessage {
+
+ protected String type;
+
+ public AbstractNotificationMessage(String type) {
+ this.type = type;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public abstract ObjectValue toValue();
+}
diff --git a/model/src/main/java/org/openremote/model/notification/AlertAction.java b/model/src/main/java/org/openremote/model/notification/AlertAction.java
deleted file mode 100644
index 2f4fd2029..000000000
--- a/model/src/main/java/org/openremote/model/notification/AlertAction.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.notification;
-
-import org.openremote.model.AbstractTypeHolder;
-import org.openremote.model.value.ObjectValue;
-import org.openremote.model.value.Values;
-
-
-/**
- * Wraps {@link ObjectValue}.
- */
-public class AlertAction extends AbstractTypeHolder {
-
-
- public AlertAction() {
- super(Values.createObject());
- }
-
- public AlertAction(String title, ActionType type, String appUrl) {
- setTitle(title);
- setActionType(type);
- setAppUrl(appUrl);
- }
-
- // TODO This should use AttributeState, do this when Android Console project has dependency on Model
- public AlertAction(String title, ActionType type, String assetId, String attributeName, String rawJson) {
- setTitle(title);
- setActionType(type);
- setAssetId(assetId);
- setAttributeName(attributeName);
- setRawJson(rawJson);
- }
-
- private void setRawJson(String rawJson) {
- if (rawJson != null) {
- objectValue.put("rawJson", Values.create(rawJson));
- } else if (objectValue.hasKey("rawJson")) {
- objectValue.remove("rawJson");
- }
- }
-
- private void setAttributeName(String attributeName) {
- if (attributeName != null) {
- objectValue.put("attributeName", Values.create(attributeName));
- } else if (objectValue.hasKey("attributeName")) {
- objectValue.remove("attributeName");
- }
- }
-
- public String getTitle() {
- return objectValue.getString("title").orElse(null);
- }
-
- public void setTitle(String title) {
- if (title != null) {
- objectValue.put("title", Values.create(title));
- } else if (objectValue.hasKey("title")) {
- objectValue.remove("title");
- }
- }
-
- public ActionType getActionType() {
- return getType().map(ActionType::valueOf).orElse(null);
- }
-
- public void setActionType(ActionType type) {
- setType(type != null ? type.name() : null);
- }
-
- public void setAssetId(String assetId) {
- if (assetId != null) {
- objectValue.put("assetId", Values.create(assetId));
- } else if (objectValue.hasKey("assetId")) {
- objectValue.remove("assetId");
- }
- }
-
- public void setAppUrl(String appUrl) {
- if (appUrl != null) {
- objectValue.put("appUrl", Values.create(appUrl));
- } else {
- objectValue.remove("appUrl");
- }
- }
-}
diff --git a/model/src/main/java/org/openremote/model/notification/AlertNotification.java b/model/src/main/java/org/openremote/model/notification/AlertNotification.java
deleted file mode 100644
index 4e1a0ed80..000000000
--- a/model/src/main/java/org/openremote/model/notification/AlertNotification.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.notification;
-
-import org.openremote.model.value.ArrayValue;
-import org.openremote.model.value.Values;
-
-import javax.persistence.*;
-import javax.validation.constraints.NotNull;
-
-import java.util.Date;
-
-import static org.openremote.model.Constants.PERSISTENCE_JSON_ARRAY_TYPE;
-import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
-
-@Entity
-@Table(name = "ALERT_NOTIFICATION")
-public class AlertNotification {
-
- @Id
- @Column(name = "ID")
- @GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)
- private Long id;
-
- @NotNull
- @Column(name = "TITLE", nullable = false)
- private String title;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
- @org.hibernate.annotations.CreationTimestamp
- protected Date createdOn;
-
- @NotNull
- @Column(name = "MESSAGE", nullable = false)
- private String message;
-
- @Column(name = "ACTIONS", columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_ARRAY_TYPE)
- private ArrayValue actions = Values.createArray();
-
- @NotNull
- @Column(name = "APP_URL", nullable = false)
- private String appUrl;
-
- @NotNull()
- @Column(name = "USER_ID")
- private String userId;
-
- @NotNull()
- @Column(name = "DELIVERY_STATUS")
- @Enumerated(EnumType.STRING)
- private DeliveryStatus deliveryStatus;
-
- public AlertNotification() {
- }
-
- public AlertNotification(String title, String message) {
- this.title = title;
- this.message = message;
- }
-
- public AlertNotification(String title, String message, String appUrl) {
- this.title = title;
- this.message = message;
- this.appUrl = appUrl;
- }
-
- /* Actuator */
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public void setActions(ArrayValue actions) {
- this.actions = actions;
- }
-
- public ArrayValue getActions() {
- return actions;
- }
-
- public void addAction(AlertAction action) {
- this.actions.add(action.getObjectValue());
- }
-
- public void addLinkAction(String title, String url) {
- AlertAction action = new AlertAction();
- action.setActionType(ActionType.LINK);
- action.setTitle(title);
- action.setAppUrl(url);
- // TODO: Remove below once consoles updated to use action appUrl
- setAppUrl(url);
- addAction(action);
- }
-
- public void addActuatorAction(String title, String assetId, String attributeName, String rawJson ) {
- AlertAction action = new AlertAction(title, ActionType.ACTUATOR, assetId, attributeName, rawJson);
- addAction(action);
- }
-
- public String getAppUrl() {
- return appUrl;
- }
-
- public void setAppUrl(String appUrl) {
- this.appUrl = appUrl;
- }
-
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public DeliveryStatus getDeliveryStatus() {
- return deliveryStatus;
- }
-
- public void setDeliveryStatus(DeliveryStatus deliveryStatus) {
- this.deliveryStatus = deliveryStatus;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "id=" + id +
- ", title='" + title + '\'' +
- ", createdOn=" + createdOn +
- ", message='" + message + '\'' +
- ", actions=" + actions +
- ", appUrl='" + appUrl + '\'' +
- ", userId='" + userId + '\'' +
- ", deliveryStatus=" + deliveryStatus +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/notification/DeviceNotificationToken.java b/model/src/main/java/org/openremote/model/notification/DeviceNotificationToken.java
deleted file mode 100644
index 5d80c7520..000000000
--- a/model/src/main/java/org/openremote/model/notification/DeviceNotificationToken.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.notification;
-
-import javax.persistence.*;
-import java.io.Serializable;
-import java.util.Date;
-
-@Entity
-@Table(name = "DEVICE_NOTIFICATION_TOKEN")
-public class DeviceNotificationToken {
-
- /**
- * The user can only store one token per device.
- */
- static public class Id implements Serializable {
-
- @Column(name = "DEVICE_ID")
- protected String deviceId;
-
- @Column(name = "USER_ID", length = 36)
- protected String userId;
-
- protected Id() {
- }
-
- public Id(String deviceId, String userId) {
- this.deviceId = deviceId;
- this.userId = userId;
- }
-
- public String getDeviceId() {
- return deviceId;
- }
-
- public String getUserId() {
- return userId;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Id id = (Id) o;
-
- return deviceId.equals(id.deviceId) && userId.equals(id.userId);
- }
-
- @Override
- public int hashCode() {
- int result = deviceId.hashCode();
- result = 31 * result + userId.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "deviceId='" + deviceId + '\'' +
- ", userId='" + userId + '\'' +
- '}';
- }
- }
-
- @EmbeddedId
- protected Id id;
-
- @Column(name = "TOKEN", nullable = false, length = 4096)
- protected String token;
-
- @Column(name = "DEVICE_TYPE")
- protected String deviceType;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "UPDATED_ON", nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
- protected Date updatedOn;
-
- public DeviceNotificationToken() {
- }
-
- public DeviceNotificationToken(Id id, String token, String deviceType) {
- this.id = id;
- this.token = token;
- this.deviceType = deviceType;
- }
-
- public Id getId() {
- return id;
- }
-
- public void setId(Id id) {
- this.id = id;
- }
-
- public String getToken() {
- return token;
- }
-
- public void setToken(String token) {
- this.token = token;
- }
-
- public String getDeviceType() {
- return deviceType;
- }
-
- public void setDeviceType(String deviceType) {
- this.deviceType = deviceType;
- }
-
- public Date getUpdatedOn() {
- return updatedOn;
- }
-
- public void setUpdatedOn(Date updatedOn) {
- this.updatedOn = updatedOn;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "id=" + id +
- ", token='" + token + '\'' +
- ", deviceType='" + deviceType + '\'' +
- ", updatedOn=" + updatedOn +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/notification/Notification.java b/model/src/main/java/org/openremote/model/notification/Notification.java
new file mode 100644
index 000000000..e7d983a28
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/Notification.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.List;
+
+public class Notification {
+
+ public enum Source {
+ INTERNAL,
+ CLIENT,
+ GLOBAL_RULESET,
+ TENANT_RULESET,
+ ASSET_RULESET
+ }
+
+ public enum TargetType {
+ TENANT,
+ USER,
+ ASSET
+ }
+
+ public static class Targets {
+
+ protected TargetType type;
+ protected String[] ids;
+
+ @JsonCreator
+ public Targets(@JsonProperty("type") TargetType type, @JsonProperty("ids") List<String> ids) {
+ this(type, ids.toArray(new String[ids.size()]));
+ }
+
+ public Targets(@JsonProperty("type") TargetType type, String...ids) {
+ this.type = type;
+ this.ids = ids;
+ }
+
+ public TargetType getType() {
+ return type;
+ }
+
+ public void setIds(String[] ids) {
+ this.ids = ids;
+ }
+
+ public String[] getIds() {
+ return ids;
+ }
+
+
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName()+ "{" +
+ "type=" + type +
+ ", ids=" + (ids != null ? "[" + String.join(",", ids) + "]" : null) +
+ '}';
+ }
+ }
+
+ public static final String HEADER_SOURCE = Notification.class.getName() + ".SOURCE";
+ public static final String HEADER_SOURCE_ID = Notification.class.getName() + ".SOURCEID";
+
+ protected String name;
+ protected AbstractNotificationMessage message;
+ protected RepeatFrequency repeatFrequency;
+ protected String repeatInterval;
+ protected Targets targets;
+
+ @JsonCreator
+ public Notification(@JsonProperty("name") String name, @JsonProperty("message") AbstractNotificationMessage message, @JsonProperty("targets") Targets targets) {
+ this.name = name;
+ this.message = message;
+ this.targets = targets;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Notification setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public AbstractNotificationMessage getMessage() {
+ return message;
+ }
+
+ public Notification setMessage(AbstractNotificationMessage message) {
+ this.message = message;
+ return this;
+ }
+
+ public Targets getTargets() {
+ return targets;
+ }
+
+ public void setTargets(Targets targets) {
+ this.targets = targets;
+ }
+
+ public RepeatFrequency getRepeatFrequency() {
+ return repeatFrequency;
+ }
+
+ public Notification setRepeatFrequency(RepeatFrequency repeatFrequency) {
+ this.repeatFrequency = repeatFrequency;
+ return this;
+ }
+
+ public String getRepeatInterval() {
+ return repeatInterval;
+ }
+
+ public Notification setRepeatInterval(String repeatInterval) {
+ this.repeatInterval = repeatInterval;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName()+ "{" +
+ "name='" + name + '\'' +
+ ", message=" + message +
+ ", repeatFrequency=" + repeatFrequency +
+ ", repeatInterval='" + repeatInterval + '\'' +
+ ", targets=" + targets +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/NotificationResource.java b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
index 29aab35ff..e1bbb42a3 100644
--- a/model/src/main/java/org/openremote/model/notification/NotificationResource.java
+++ b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
@@ -22,10 +22,10 @@ package org.openremote.model.notification;
import jsinterop.annotations.JsType;
import org.openremote.model.http.RequestParams;
import org.openremote.model.http.SuccessStatusCode;
+import org.openremote.model.value.Value;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
import java.util.List;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@@ -35,112 +35,95 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
public interface NotificationResource {
/**
- * Store a device token for the authenticated user.
- */
- @PUT
- @Path("token")
- @SuccessStatusCode(204)
- @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
- @RolesAllowed({"write:user"})
- @SuppressWarnings("unusable-by-js")
- void storeDeviceToken(@BeanParam RequestParams requestParams,
- @FormParam("device_id") String deviceId,
- @FormParam("token") String token,
- @FormParam("device_type") String deviceType);
-
- /**
+ * Gets all sent notifications that have been sent to the specified targets; optionally limiting the scope of the
+ * request by {@link AbstractNotificationMessage} type and/or sent datetime. If type(s) or timestamp are not set
+ * then it is assumed no type or time constraint is required.
+ * <p>
* Only the superuser can call this operation.
*/
@GET
- @Path("token/{userId}")
+ @SuccessStatusCode(200)
@Produces(APPLICATION_JSON)
@RolesAllowed({"read:admin"})
@SuppressWarnings("unusable-by-js")
- List<DeviceNotificationToken> getDeviceTokens(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId);
+ SentNotification[] getNotifications(@BeanParam RequestParams requestParams,
+ @QueryParam("types") List<String> types,
+ @QueryParam("before") Long timestamp,
+ @QueryParam("tenantId") List<String> tenantIds,
+ @QueryParam("userId") List<String> userIds,
+ @QueryParam("assetId") List<String> assetIds);
/**
+ * Removes all sent notifications that have been sent to the specified targets; optionally limiting the scope of the
+ * request by {@link AbstractNotificationMessage} type and/or sent datetime. If type(s) or timestamp are not set
+ * then it is assumed no type or time constraint is required.
+ * <p>
* Only the superuser can call this operation.
*/
@DELETE
- @Path("token/{userId}/device/{deviceId}")
- @Produces(APPLICATION_JSON)
- @RolesAllowed({"write:admin"})
- @SuppressWarnings("unusable-by-js")
- void deleteDeviceToken(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId,
- @PathParam("deviceId") String deviceId);
-
- @POST
- @Path("alert")
@SuccessStatusCode(204)
- @Consumes(APPLICATION_JSON)
- @RolesAllowed({"write:user"})
+ @RolesAllowed({"write:admin"})
@SuppressWarnings("unusable-by-js")
- void storeNotificationForCurrentUser(@BeanParam RequestParams requestParams,
- AlertNotification alertNotification);
+ void removeNotifications(@BeanParam RequestParams requestParams,
+ @QueryParam("types") List<String> types,
+ @QueryParam("before") Long timestamp,
+ @QueryParam("tenantId") List<String> tenantIds,
+ @QueryParam("userId") List<String> userIds,
+ @QueryParam("assetId") List<String> assetIds);
/**
+ * Remove a specific sent notification by ID.
+ * <p>
* Only the superuser can call this operation.
*/
- @POST
- @Path("alert/user/{userId}")
+ @DELETE
+ @Path("{notificationId}")
@SuccessStatusCode(204)
- @Consumes(APPLICATION_JSON)
@RolesAllowed({"write:admin"})
@SuppressWarnings("unusable-by-js")
- void storeNotificationForUser(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId,
- AlertNotification alertNotification);
+ void removeNotification(@BeanParam RequestParams requestParams,
+ @PathParam("notificationId") Long notificationId);
/**
- * Only the superuser can call this operation.
+ * Send a notification to one or more targets; the authorisation of the requesting user will determine whether or
+ * not the targets can be contacted; if one or more targets are not accessible due to permissions then the entire
+ * request will fail with a 403 response.
*/
- @GET
- @Path("alert/user/{userId}")
- @SuccessStatusCode(200)
- @Produces(APPLICATION_JSON)
- @RolesAllowed({"read:admin"})
+ @POST
+ @Path("alert")
+ @SuccessStatusCode(204)
+ @Consumes(APPLICATION_JSON)
+ @RolesAllowed({"write:user"})
@SuppressWarnings("unusable-by-js")
- AlertNotification[] getNotificationsOfUser(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId);
+ void sendNotification(@BeanParam RequestParams requestParams,
+ Notification notification);
/**
- * Only the superuser can call this operation.
+ * Allows a target to mark a notification as delivered.
+ * <p>
+ * The requesting user must have permission to acknowledge the specified notification otherwise a 403 response
+ * is returned.
*/
- @DELETE
- @Path("alert/user/{userId}")
+ @PUT
+ @Path("{notificationId}/delivered")
@SuccessStatusCode(204)
- @RolesAllowed({"write:admin"})
@SuppressWarnings("unusable-by-js")
- void removeNotificationsOfUser(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId);
+ void notificationDelivered(@BeanParam RequestParams requestParams,
+ @QueryParam("targetId") String targetId,
+ @PathParam("notificationId") Long notificationId);
/**
- * Only the superuser can call this operation.
+ * Allows a target to acknowledge a notification with an optional acknowledgement value.
+ * <p>
+ * The requesting user must have permission to acknowledge the specified notification otherwise a 403 response
+ * is returned.
*/
- @DELETE
- @Path("alert/user/{userId}/{alertId}")
- @SuccessStatusCode(204)
- @RolesAllowed({"write:admin"})
- @SuppressWarnings("unusable-by-js")
- void removeNotification(@BeanParam RequestParams requestParams,
- @PathParam("userId") String userId,
- @PathParam("alertId") Long id);
-
- // TODO Fails silently on native apps when called with expired offline token?
- @GET
- @Path("alert")
- @Produces(APPLICATION_JSON)
- @RolesAllowed({"write:user"})
- @SuppressWarnings("unusable-by-js")
- List<AlertNotification> getQueuedNotificationsOfCurrentUser(@BeanParam RequestParams requestParams);
-
- @DELETE
- @Path("alert/{alertId}")
+ @PUT
+ @Path("{notificationId}/acknowledged")
@SuccessStatusCode(204)
- @RolesAllowed({"write:user"})
@SuppressWarnings("unusable-by-js")
- void ackNotificationOfCurrentUser(@BeanParam RequestParams requestParams,
- @PathParam("alertId") Long id);
+ void notificationAcknowledged(@BeanParam RequestParams requestParams,
+ @QueryParam("targetId") String targetId,
+ @PathParam("notificationId") Long notificationId,
+ Value acknowledgement);
}
diff --git a/model/src/main/java/org/openremote/model/notification/NotificationSendResult.java b/model/src/main/java/org/openremote/model/notification/NotificationSendResult.java
new file mode 100644
index 000000000..8d82ed394
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/NotificationSendResult.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+public class NotificationSendResult {
+
+ protected boolean success;
+ protected String message;
+
+ protected NotificationSendResult(boolean success, String message) {
+ this.success = success;
+ this.message = message;
+ }
+
+ public boolean isSuccess() {
+ return success;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public static NotificationSendResult success() {
+ return new NotificationSendResult(true, null);
+ }
+
+ public static NotificationSendResult failure(String message) {
+ return new NotificationSendResult(false, message);
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java b/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java
new file mode 100644
index 000000000..d544f921a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD;
+import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl;
+
+
+public class PushNotificationAction {
+
+ protected String url;
+ protected String httpMethod;
+ protected Value data;
+ protected boolean silent;
+ protected boolean openInBrowser; // For app based consoles (i.e. Android and iOS)
+
+ public PushNotificationAction(String url) {
+ this.url = url;
+ }
+
+ public PushNotificationAction(String url, Value data, boolean silent, boolean openInBrowser, String httpMethod) {
+ this.url = url;
+ this.data = data;
+ this.silent = silent;
+ this.openInBrowser = openInBrowser;
+ this.httpMethod = httpMethod;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public Value getData() {
+ return data;
+ }
+
+ public void setData(Value data) {
+ this.data = data;
+ }
+
+ public boolean isSilent() {
+ return silent;
+ }
+
+ public void setSilent(boolean silent) {
+ this.silent = silent;
+ }
+
+ public boolean isOpenInBrowser() {
+ return openInBrowser;
+ }
+
+ public void setOpenInBrowser(boolean openInBrowser) {
+ this.openInBrowser = openInBrowser;
+ }
+
+ public String getHttpMethod() {
+ return httpMethod;
+ }
+
+ public void setHttpMethod(String httpMethod) {
+ this.httpMethod = httpMethod;
+ }
+
+ public ObjectValue toValue() {
+ ObjectValue val = Values.createObject();
+ val.put("url", url);
+ if (!TextUtil.isNullOrEmpty(httpMethod)) {
+ val.put("httpMethod", httpMethod);
+ }
+ val.put("silent", silent);
+ val.put("openInBrowser", openInBrowser);
+ if (data != null) {
+ val.put("data", data);
+ }
+ return val;
+ }
+
+ public static PushNotificationAction writeAttributeValueAction(AttributeRef attributeRef, Value value) {
+ String url = getWriteAttributeUrl(attributeRef);
+ return new PushNotificationAction(url, value, true, false, WRITE_ATTRIBUTE_HTTP_METHOD);
+ }
+
+ public static PushNotificationAction fromValue(ObjectValue value) {
+ if (value == null) {
+ return null;
+ }
+
+ return new PushNotificationAction(
+ value.getString("url").orElse(null),
+ value.get("data").orElse(null),
+ value.getBoolean("silent").orElse(false),
+ value.getBoolean("openInBrowser").orElse(false),
+ value.getString("httpMethod").orElse(null)
+ );
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/PushNotificationButton.java b/model/src/main/java/org/openremote/model/notification/PushNotificationButton.java
new file mode 100644
index 000000000..cf4c3fad4
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/PushNotificationButton.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+/**
+ * Represents an action button that can be shown on push alerts (dependent on console support)
+ */
+public class PushNotificationButton {
+
+ protected String title;
+ protected PushNotificationAction action;
+
+ public PushNotificationButton(String title, PushNotificationAction action) {
+ this.title = title;
+ this.action = action;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public PushNotificationAction getAction() {
+ return action;
+ }
+
+ public void setAction(PushNotificationAction action) {
+ this.action = action;
+ }
+
+ public ObjectValue toValue() {
+ ObjectValue val = Values.createObject();
+ val.put("title", title);
+ if (action != null) {
+ val.put("action", action.toValue());
+ }
+
+ return val;
+ }
+
+ public static PushNotificationButton fromValue(ObjectValue value) {
+ if (value == null) {
+ return null;
+ }
+
+ return new PushNotificationButton(
+ value.getString("title").orElse(null),
+ value.getObject("action").map(PushNotificationAction::fromValue).orElse(null)
+ );
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java
new file mode 100644
index 000000000..848c098fe
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java
@@ -0,0 +1,228 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+public class PushNotificationMessage extends AbstractNotificationMessage {
+
+ public enum TargetType {
+ DEVICE,
+ TOPIC,
+ CONDITION
+ }
+
+ public enum MessagePriority {
+ NORMAL,
+ HIGH
+ }
+
+ public static final String TYPE = "push";
+
+ protected String title;
+ protected String body;
+ protected PushNotificationAction action;
+ protected List<PushNotificationButton> buttons;
+ protected ObjectValue data;
+ protected MessagePriority priority;
+ protected TargetType targetType;
+ protected String target;
+ protected Long ttlSeconds;
+
+ @JsonCreator
+ public PushNotificationMessage(@JsonProperty("title") String title,
+ @JsonProperty("body") String body,
+ @JsonProperty("action") PushNotificationAction action,
+ @JsonProperty("buttons") List<PushNotificationButton> buttons,
+ @JsonProperty("data") ObjectValue data,
+ @JsonProperty("priority") MessagePriority priority,
+ @JsonProperty("targetType") TargetType targetType,
+ @JsonProperty("target") String target,
+ @JsonProperty("expiration") Long ttlSeconds) {
+ super(TYPE);
+ this.title = title;
+ this.body = body;
+ this.action = action;
+ this.buttons = buttons;
+ this.priority = priority;
+ this.targetType = targetType;
+ this.target = target;
+ this.data = data;
+ this.ttlSeconds = ttlSeconds;
+ }
+
+ public PushNotificationMessage(String title,
+ String body,
+ PushNotificationAction action,
+ List<PushNotificationButton> buttons,
+ ObjectValue data) {
+ super(TYPE);
+ this.title = title;
+ this.body = body;
+ this.action = action;
+ this.buttons = buttons;
+ this.data = data;
+ }
+
+ public PushNotificationMessage() {
+ super(TYPE);
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public PushNotificationMessage setTitle(String title) {
+ this.title = title;
+ return this;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public PushNotificationMessage setBody(String body) {
+ this.body = body;
+ return this;
+ }
+
+ public PushNotificationAction getAction() {
+ return action;
+ }
+
+ public PushNotificationMessage setAction(PushNotificationAction action) {
+ this.action = action;
+ return this;
+ }
+
+ public List<PushNotificationButton> getButtons() {
+ return buttons;
+ }
+
+ public PushNotificationMessage setButtons(List<PushNotificationButton> buttons) {
+ this.buttons = buttons;
+ return this;
+ }
+
+ public ObjectValue getData() {
+ return data;
+ }
+
+ public PushNotificationMessage setData(ObjectValue data) {
+ this.data = data;
+ return this;
+ }
+
+ public MessagePriority getPriority() {
+ return priority;
+ }
+
+ public PushNotificationMessage setPriority(MessagePriority priority) {
+ this.priority = priority;
+ return this;
+ }
+
+ public TargetType getTargetType() {
+ return targetType;
+ }
+
+ public PushNotificationMessage setTargetType(TargetType targetType) {
+ this.targetType = targetType;
+ return this;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+
+ public PushNotificationMessage setTarget(String target) {
+ this.target = target;
+ return this;
+ }
+
+ public Long getTtlSeconds() {
+ return ttlSeconds;
+ }
+
+ public PushNotificationMessage setTtlSeconds(Long ttlSeconds) {
+ this.ttlSeconds = ttlSeconds;
+ return this;
+ }
+
+ @Override
+ public ObjectValue toValue() {
+ ObjectValue val = Values.createObject();
+ if (!isNullOrEmpty(title)) {
+ val.put("title", title);
+ }
+ if (!isNullOrEmpty(body)) {
+ val.put("body", body);
+ }
+ if (action != null) {
+ val.put("action", action.toValue());
+ }
+ if (buttons != null && !buttons.isEmpty()) {
+ ArrayValue arrVal = Values.createArray();
+ arrVal.addAll(buttons.stream().map(PushNotificationButton::toValue).toArray(ObjectValue[]::new));
+ val.put("buttons", arrVal);
+ }
+ if (data != null) {
+ val.put("data", data);
+ }
+ if (priority != null) {
+ val.put("priority", Values.create(priority.name()));
+ }
+ if (targetType != null) {
+ val.put("targetType", Values.create(targetType.name()));
+ }
+ if (!isNullOrEmpty(target)) {
+ val.put("target", Values.create(target));
+ }
+ if (ttlSeconds != null) {
+ val.put("ttlSeconds", Values.create(ttlSeconds));
+ }
+ return val;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "title='" + title + '\'' +
+ ", body='" + body + '\'' +
+ ", action=" + action +
+ ", buttons=" + buttons +
+ ", data=" + data +
+ ", priority=" + priority +
+ ", targetType=" + targetType +
+ ", target='" + target + '\'' +
+ ", ttlSeconds=" + ttlSeconds +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMMessagePriority.java b/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
similarity index 85%
rename from manager/src/main/java/org/openremote/manager/notification/FCMMessagePriority.java
rename to model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
index 7bb2e8bdd..996337514 100644
--- a/manager/src/main/java/org/openremote/manager/notification/FCMMessagePriority.java
+++ b/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
@@ -17,9 +17,13 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.notification;
+package org.openremote.model.notification;
-public enum FCMMessagePriority {
- NORMAL,
- HIGH
+public enum RepeatFrequency {
+ ALWAYS,
+ ONCE,
+ DAILY,
+ WEEKLY,
+ MONTHLY,
+ ANNUALLY
}
diff --git a/model/src/main/java/org/openremote/model/notification/SentNotification.java b/model/src/main/java/org/openremote/model/notification/SentNotification.java
new file mode 100644
index 000000000..bad7b93d7
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/notification/SentNotification.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.notification;
+
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+import javax.persistence.*;
+import javax.validation.constraints.NotNull;
+import java.util.Date;
+
+import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;
+import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
+
+@Entity
+@Table(name = "NOTIFICATION")
+public class SentNotification {
+
+ @Id
+ @Column(name = "ID")
+ @GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)
+ protected Long id;
+
+ @NotNull
+ @Column(name = "NAME", nullable = false)
+ protected String name;
+
+ @NotNull
+ @Column(name = "TYPE", nullable = false)
+ protected String type;
+
+ @NotNull
+ @Column(name = "TARGET")
+ @Enumerated(EnumType.STRING)
+ protected Notification.TargetType target;
+
+ @NotNull
+ @Column(name = "TARGET_ID")
+ protected String targetId;
+
+ @NotNull()
+ @Column(name = "SOURCE")
+ @Enumerated(EnumType.STRING)
+ protected Notification.Source source;
+
+ @Column(name = "SOURCE_ID")
+ protected String sourceId;
+
+ @Column(name = "MESSAGE", columnDefinition = "jsonb")
+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)
+ protected ObjectValue message;
+
+ @Column(name = "ERROR")
+ protected String error;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "SENT_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ @org.hibernate.annotations.CreationTimestamp
+ protected Date sentOn;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "DELIVERED_ON", columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date deliveredOn;
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "ACKNOWLEDGED_ON", columnDefinition = "TIMESTAMP WITH TIME ZONE")
+ protected Date acknowledgedOn;
+
+ @Column(name = "ACKNOWLEDGEMENT")
+ protected String acknowledgement;
+
+ public Long getId() {
+ return id;
+ }
+
+ public SentNotification setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public SentNotification setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public SentNotification setType(String type) {
+ this.type = type;
+ return this;
+ }
+
+ public Date getSentOn() {
+ return sentOn;
+ }
+
+ public SentNotification setSentOn(Date sentOn) {
+ this.sentOn = sentOn;
+ return this;
+ }
+
+ public Notification.Source getSource() {
+ return source;
+ }
+
+ public SentNotification setSource(Notification.Source source) {
+ this.source = source;
+ return this;
+ }
+
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ public SentNotification setSourceId(String sourceId) {
+ this.sourceId = sourceId;
+ return this;
+ }
+
+ public Notification.TargetType getTarget() {
+ return target;
+ }
+
+ public SentNotification setTarget(Notification.TargetType target) {
+ this.target = target;
+ return this;
+ }
+
+ public String getTargetId() {
+ return targetId;
+ }
+
+ public SentNotification setTargetId(String targetId) {
+ this.targetId = targetId;
+ return this;
+ }
+
+ public ObjectValue getMessage() {
+ return message == null ? message = Values.createObject() : message;
+ }
+
+ public SentNotification setMessage(ObjectValue message) {
+ this.message = message;
+ return this;
+ }
+
+ public Date getDeliveredOn() {
+ return deliveredOn;
+ }
+
+ public SentNotification setDeliveredOn(Date deliveredOn) {
+ this.deliveredOn = deliveredOn;
+ return this;
+ }
+
+ public Date getAcknowledgedOn() {
+ return acknowledgedOn;
+ }
+
+ public SentNotification setAcknowledgedOn(Date acknowledgedOn) {
+ this.acknowledgedOn = acknowledgedOn;
+ return this;
+ }
+
+ public String getAcknowledgement() {
+ return acknowledgement;
+ }
+
+ public SentNotification setAcknowledgement(String acknowledgement) {
+ this.acknowledgement = acknowledgement;
+ return this;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public SentNotification setError(String error) {
+ this.error = error;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id=" + id +
+ ", name='" + name + '\'' +
+ ", type='" + type + '\'' +
+ ", target=" + target +
+ ", targetId='" + targetId + '\'' +
+ ", source=" + source +
+ ", sourceId='" + sourceId + '\'' +
+ ", message=" + message +
+ ", sentOn=" + sentOn +
+ ", deliveredOn=" + deliveredOn +
+ ", acknowledgedOn=" + acknowledgedOn +
+ ", acknowledgement='" + acknowledgement + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetQuery.java b/model/src/main/java/org/openremote/model/query/AssetQuery.java
similarity index 96%
rename from model/src/main/java/org/openremote/model/asset/AssetQuery.java
rename to model/src/main/java/org/openremote/model/query/AssetQuery.java
index c3084a892..095869575 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetQuery.java
+++ b/model/src/main/java/org/openremote/model/query/AssetQuery.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.model.asset;
+package org.openremote.model.query;
/**
* This was only done to allow GWT jackson to compile it; don't think GWT jackson
diff --git a/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
new file mode 100644
index 000000000..f8a501ab0
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
@@ -0,0 +1,493 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query;
+
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.asset.CalendarEventConfiguration;
+import org.openremote.model.query.filter.*;
+import org.openremote.model.value.*;
+
+import java.util.*;
+
+/**
+ * Encapsulate asset query restriction, projection, and ordering of results.
+ */
+// TODO: Add AssetQuery support for arbitrary attribute property path amd value (e.g. attributes.consoleProviders.geofence.version == "ORConsole")
+@SuppressWarnings("unchecked")
+public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
+
+ public enum Include {
+ ALL_EXCEPT_PATH_AND_ATTRIBUTES,
+ ALL_EXCEPT_PATH,
+ ONLY_ID_AND_NAME,
+ ONLY_ID_AND_NAME_AND_ATTRIBUTES,
+ ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES,
+ ALL
+ }
+
+ public enum Access {
+ PRIVATE_READ,
+ RESTRICTED_READ,
+ PUBLIC_READ
+ }
+
+ /**
+ * String matching options
+ */
+ public enum Match {
+ EXACT,
+ NOT_EXACT,
+ BEGIN,
+ END,
+ CONTAINS;
+
+ public String prepare(String string) {
+ if (string == null)
+ return null;
+ switch (this) {
+ case BEGIN:
+ return string + "%";
+ case CONTAINS:
+ return "%" + string + "%";
+ case END:
+ return "%" + string;
+ }
+ return string;
+ }
+ }
+
+ /**
+ * Binary operators
+ */
+ public enum Operator {
+ EQUALS,
+ NOT_EQUALS,
+ GREATER_THAN,
+ GREATER_EQUALS,
+ LESS_THAN,
+ LESS_EQUALS,
+ BETWEEN
+ }
+
+ public enum NumberType {
+ DOUBLE,
+ INTEGER
+ }
+
+ public static class Select {
+
+ public Include include;
+ public boolean recursive;
+ public Access access;
+ public String[] attributeNames;
+
+ public Select() {
+ }
+
+ public Select(Include include) {
+ this(include, Access.PRIVATE_READ);
+ }
+
+ public Select(Include include, Access access) {
+ this(include, false, access);
+ }
+
+ public Select(Include include, boolean recursive, Access access) {
+ this(include, recursive, access, (String[]) null);
+ }
+
+ public Select(Include include, boolean recursive, String... attributeNames) {
+ this(include, recursive, Access.PRIVATE_READ, attributeNames);
+ }
+
+ public Select(Include include, boolean recursive, Access access, String... attributeNames) {
+ if (include == null) {
+ include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
+ }
+ this.include = include;
+ this.access = access;
+ this.recursive = recursive;
+ this.attributeNames = attributeNames;
+ }
+
+ public static Select fromObjectValue(ObjectValue objectValue) {
+ Select select = new Select();
+ objectValue.getString("include").ifPresent(include -> {
+ select.include = Include.valueOf(include);
+ });
+ objectValue.getString("access").ifPresent(access -> {
+ select.access = Access.valueOf(access);
+ });
+ objectValue.getBoolean("recursive").ifPresent(recursive -> {
+ select.recursive = recursive;
+ });
+ objectValue.getArray("attributeNames").ifPresent(attributeNames -> {
+ select.attributeNames = attributeNames.stream()
+ .map(value -> (StringValue) value)
+ .map(StringValue::getString)
+ .toArray(String[]::new);
+ });
+ return select;
+ }
+
+ public Select include(Include include) {
+ this.include = include;
+ return this;
+ }
+
+ public Select filterAccess(Access access) {
+ this.access = access;
+ return this;
+ }
+
+ public Select filterAttributes(String... attributeNames) {
+ this.attributeNames = attributeNames;
+ return this;
+ }
+
+ public Select recursive(boolean recursive) {
+ this.recursive = recursive;
+ return this;
+ }
+
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("include", Values.create(include.toString()));
+ objectValue.put("recursive", Values.create(recursive));
+ objectValue.put("access", Values.create(access.toString()));
+ objectValue.put("attributeNames",
+ Values.createArray().addAll(Arrays.stream(attributeNames).map(Values::create).toArray(Value[]::new)));
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "include=" + include +
+ ", recursive=" + recursive +
+ ", access=" + access +
+ ", attributeNames=" + Arrays.toString(attributeNames) +
+ '}';
+ }
+ }
+
+ public static class OrderBy {
+
+ public enum Property {
+ CREATED_ON,
+ NAME,
+ ASSET_TYPE,
+ PARENT_ID,
+ REALM_ID
+ }
+
+ public Property property;
+ public boolean descending;
+
+ public OrderBy() {
+ }
+
+ public OrderBy(Property property) {
+ this.property = property;
+ }
+
+ public OrderBy(Property property, boolean descending) {
+ this.property = property;
+ this.descending = descending;
+ }
+
+ public OrderBy property(Property property) {
+ this.property = property;
+ return this;
+ }
+
+ public OrderBy descending(boolean descending) {
+ this.descending = descending;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "property=" + property +
+ ", descending=" + descending +
+ '}';
+ }
+ }
+ // Projection
+ public Select select;
+ // Restriction predicates
+ public List<String> ids;
+ public StringPredicate name;
+ public ParentPredicate parent;
+ public PathPredicate path;
+ public TenantPredicate tenant;
+ public String userId;
+ public StringPredicate type;
+ public AttributePredicate[] attribute;
+ public AttributeMetaPredicate[] attributeMeta;
+ public CalendarEventActivePredicate calendarEventActive;
+ public LocationPredicate location;
+ // Ordering
+ public OrderBy orderBy;
+ protected BaseAssetQuery() {
+ }
+
+ public static final ArrayValue queriesAsValue(BaseAssetQuery... queries) {
+ ArrayValue arrayValue = Values.createArray();
+
+ for (BaseAssetQuery query : queries) {
+ ObjectValue objectValue = Values.createObject();
+ if (query.select != null) {
+ objectValue.put("select", query.select.toModelValue());
+ }
+ if (query.type != null) {
+ objectValue.put("type", query.type.toModelValue());
+ }
+ if (query.attribute != null && query.attribute.length > 0) {
+ ArrayValue attributeArray = Values.createArray();
+ for (AttributePredicate attributePredicate : query.attribute) {
+ attributeArray.add(attributePredicate.toModelValue());
+ }
+ objectValue.put("attribute", attributeArray);
+ }
+ arrayValue.add(objectValue);
+ }
+ return arrayValue;
+ }
+
+ public static final AssetQuery objectValueAsQuery(ObjectValue objectValue) {
+ AssetQuery assetQuery = new AssetQuery();
+
+ objectValue.getObject("select").ifPresent(selectValue -> {
+ assetQuery.select = Select.fromObjectValue(selectValue);
+ });
+
+ objectValue.getObject("type").ifPresent(typeValue -> {
+ assetQuery.type = StringPredicate.fromObjectValue(typeValue);
+ });
+
+ objectValue.getArray("attribute").ifPresent(attributeValue -> {
+ assetQuery.attribute = attributeValue.stream()
+ .map(val -> (ObjectValue) val)
+ .map(attributePredicateValue -> {
+ AttributePredicate attributePredicate = new AttributePredicate();
+
+ attributePredicate.name = StringPredicate.fromObjectValue(attributePredicateValue
+ .getObject("name")
+ .orElseThrow(() -> new IllegalArgumentException(
+ "StringPredicate missing for name in AttributePredicate"))
+ );
+
+ ObjectValue predicateValue = attributePredicateValue
+ .getObject("value")
+ .orElseThrow(() -> new IllegalArgumentException("value missing in AttributePredicate"));
+
+ predicateValue.getString("predicateType").ifPresent(predicateType -> {
+ switch (predicateType) {
+ case "StringPredicate":
+ attributePredicate.value = StringPredicate.fromObjectValue(predicateValue);
+ break;
+ case "BooleanPredicate":
+ attributePredicate.value = BooleanPredicate.fromObjectValue(predicateValue);
+ break;
+ case "StringArrayPredicate":
+ attributePredicate.value = StringArrayPredicate.fromObjectValue(predicateValue);
+ break;
+ case "DateTimePredicate":
+ attributePredicate.value = DateTimePredicate.fromObjectValue(predicateValue);
+ break;
+ case "NumberPredicate":
+ attributePredicate.value = NumberPredicate.fromObjectValue(predicateValue);
+ break;
+ }
+ });
+ return attributePredicate;
+ })
+ .toArray(AttributePredicate[]::new);
+ });
+
+ return assetQuery;
+ }
+
+ public CHILD select(Select select) {
+ if (select == null) {
+ select = new Select();
+ }
+
+ this.select = select;
+ return (CHILD) this;
+ }
+
+ public CHILD id(String id) {
+ this.ids = Collections.singletonList(id);
+ return (CHILD) this;
+ }
+
+ public CHILD ids(List<String> ids) {
+ this.ids = ids;
+ return (CHILD) this;
+ }
+
+ public CHILD name(String name) {
+ return name(new StringPredicate(name));
+ }
+
+ public CHILD name(StringPredicate name) {
+ this.name = name;
+ return (CHILD) this;
+ }
+
+ public CHILD parent(String id) {
+ return parent(new ParentPredicate(id));
+ }
+
+ public CHILD parent(AssetType assetType) {
+ return parent(new ParentPredicate().type(assetType));
+ }
+
+ public CHILD parent(ParentPredicate parentPredicate) {
+ this.parent = parentPredicate;
+ return (CHILD) this;
+ }
+
+ public CHILD path(PathPredicate pathPredicate) {
+ this.path = pathPredicate;
+ return (CHILD) this;
+ }
+
+ public CHILD tenant(TenantPredicate tenantPredicate) {
+ this.tenant = tenantPredicate;
+ return (CHILD) this;
+ }
+
+ public CHILD userId(String userId) {
+ this.userId = userId;
+ return (CHILD) this;
+ }
+
+ public CHILD type(StringPredicate type) {
+ this.type = type;
+ return (CHILD) this;
+ }
+
+ public CHILD type(String type) {
+ return type(new StringPredicate(type));
+ }
+
+ public CHILD type(AssetType assetType) {
+ return type(new StringPredicate(assetType.getValue()));
+ }
+
+ public CHILD attributes(AttributePredicate... attributePredicates) {
+ this.attribute = attributePredicates;
+ return (CHILD) this;
+ }
+
+ public CHILD attributeName(String attributeName) {
+ return attributes(new AttributePredicate(attributeName));
+ }
+
+ public CHILD attributeName(Match match, String attributeName) {
+ return attributes(new AttributePredicate(new StringPredicate(match, attributeName)));
+ }
+
+ /**
+ * Match non-empty attribute value.
+ */
+ public CHILD attributeValue(String name) {
+ return attributes(new AttributePredicate(new StringPredicate(name), new ValueNotEmptyPredicate()));
+ }
+
+ public CHILD attributeValue(String name, ValuePredicate valuePredicate) {
+ return attributes(new AttributePredicate(new StringPredicate(name), valuePredicate));
+ }
+
+ public CHILD attributeValue(String name, boolean b) {
+ return attributeValue(name, new BooleanPredicate(b));
+ }
+
+ public CHILD attributeValue(String name, String s) {
+ return attributeValue(name, new StringPredicate(s));
+ }
+
+ public CHILD attributeValue(String name, Match match, String s) {
+ return attributeValue(name, new StringPredicate(match, s));
+ }
+
+ public CHILD attributeValue(String name, Match match, boolean caseSensitive, String s) {
+ return attributeValue(name, new StringPredicate(match, caseSensitive, s));
+ }
+
+ public CHILD attributeValue(String name, double d) {
+ return attributeValue(name, new NumberPredicate(d));
+ }
+
+ public CHILD attributeValue(String name, Operator operator, double d) {
+ return attributeValue(name, new NumberPredicate(d, operator));
+ }
+
+ public CHILD attributeMeta(AttributeMetaPredicate... attributeMetaPredicates) {
+ this.attributeMeta = attributeMetaPredicates;
+ return (CHILD) this;
+ }
+
+ public CHILD orderBy(OrderBy orderBy) {
+ this.orderBy = orderBy;
+ return (CHILD) this;
+ }
+
+ /**
+ * Will filter out assets that have a {@link CalendarEventConfiguration} attribute that results in the event not
+ * being 'active/in progress' at the specified time. Assets without a {@link CalendarEventConfiguration} attribute
+ * are assumed to always be in progress (i.e. will always pass this check).
+ *
+ * <b>
+ * NOTE: This predicate is applied in memory and the results should be limited as much as possible by applying other
+ * predicates to the query to avoid performance issues.
+ * </b>
+ */
+ public CHILD calendarEventActive(long timestampSeconds) {
+ calendarEventActive = new CalendarEventActivePredicate(timestampSeconds);
+ return (CHILD) this;
+ }
+
+ public CHILD location(LocationPredicate locationPredicate) {
+ this.location = locationPredicate;
+ return (CHILD) this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "select=" + select +
+ ", id='" + ids + '\'' +
+ ", name=" + name +
+ ", parent=" + parent +
+ ", path=" + path +
+ ", tenant=" + tenant +
+ ", userId='" + userId + '\'' +
+ ", type=" + type +
+ ", attribute=" + Arrays.toString(attribute) +
+ ", attributeMeta=" + Arrays.toString(attributeMeta) +
+ ", orderBy=" + orderBy +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/UserQuery.java b/model/src/main/java/org/openremote/model/query/UserQuery.java
new file mode 100644
index 000000000..ce70ba029
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/UserQuery.java
@@ -0,0 +1,35 @@
+package org.openremote.model.query;
+
+
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
+import org.openremote.model.query.filter.UserAssetPredicate;
+
+public class UserQuery<CHILD extends UserQuery<CHILD>> {
+
+ // Restriction predicates
+ public TenantPredicate tenantPredicate;
+ public UserAssetPredicate assetPredicate;
+ public PathPredicate pathPredicate;
+
+ public UserQuery() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public CHILD tenant(TenantPredicate tenantPredicate) {
+ this.tenantPredicate = tenantPredicate;
+ return (CHILD) this;
+ }
+
+ @SuppressWarnings("unchecked")
+ public CHILD asset(UserAssetPredicate assetPredicate) {
+ this.assetPredicate = assetPredicate;
+ return (CHILD) this;
+ }
+
+ @SuppressWarnings("unchecked")
+ public CHILD assetPath(PathPredicate pathPredicate) {
+ this.pathPredicate = pathPredicate;
+ return (CHILD) this;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java
new file mode 100644
index 000000000..abba89ca9
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.query.BaseAssetQuery;
+
+public class AttributeMetaPredicate {
+
+ public StringPredicate itemNamePredicate;
+ public ValuePredicate itemValuePredicate;
+
+ public AttributeMetaPredicate() {
+ }
+
+ public AttributeMetaPredicate(StringPredicate itemNamePredicate) {
+ this.itemNamePredicate = itemNamePredicate;
+ }
+
+ public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor) {
+ this.itemNamePredicate = new StringPredicate(metaItemDescriptor.getUrn());
+ }
+
+ public AttributeMetaPredicate(ValuePredicate itemValuePredicate) {
+ this.itemValuePredicate = itemValuePredicate;
+ }
+
+ public AttributeMetaPredicate(StringPredicate itemNamePredicate, ValuePredicate itemValuePredicate) {
+ this.itemNamePredicate = itemNamePredicate;
+ this.itemValuePredicate = itemValuePredicate;
+ }
+
+ public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor, ValuePredicate itemValuePredicate) {
+ this(new StringPredicate(metaItemDescriptor.getUrn()), itemValuePredicate);
+ }
+
+ public AttributeMetaPredicate itemName(StringPredicate itemNamePredicate) {
+ this.itemNamePredicate = itemNamePredicate;
+ return this;
+ }
+
+ public AttributeMetaPredicate itemName(MetaItemDescriptor metaItemDescriptor) {
+ return itemName(new StringPredicate(metaItemDescriptor.getUrn()));
+ }
+
+ public AttributeMetaPredicate itemValue(ValuePredicate itemValuePredicate) {
+ this.itemValuePredicate = itemValuePredicate;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "itemNamePredicate=" + itemNamePredicate +
+ ", itemValuePredicate=" + itemValuePredicate +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java
new file mode 100644
index 000000000..fd31d4865
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+public class AttributePredicate {
+
+ public StringPredicate name;
+ public ValuePredicate value;
+
+ public AttributePredicate() {
+ }
+
+ public AttributePredicate(String name) {
+ this(new StringPredicate(name));
+ }
+
+ public AttributePredicate(StringPredicate name) {
+ this.name = name;
+ }
+
+ public AttributePredicate(ValuePredicate value) {
+ this.value = value;
+ }
+
+ public AttributePredicate(StringPredicate name, ValuePredicate value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public AttributePredicate name(StringPredicate name) {
+ this.name = name;
+ return this;
+ }
+
+ public AttributePredicate value(ValuePredicate value) {
+ this.value = value;
+ return this;
+ }
+
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("name", name.toModelValue());
+ objectValue.put("value", value.toModelValue());
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "name=" + name +
+ ", value=" + value +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributeRefPredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributeRefPredicate.java
new file mode 100644
index 000000000..02ac1232e
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/AttributeRefPredicate.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.attribute.MetaItemDescriptor;
+
+public class AttributeRefPredicate extends AttributeMetaPredicate {
+
+ public AttributeRefPredicate() {
+ }
+
+ public AttributeRefPredicate(AttributeRef attributeRef) {
+ this(attributeRef.getEntityId(), attributeRef.getAttributeName());
+ }
+
+ public AttributeRefPredicate(String entityId, String attributeName) {
+ super(
+ new StringArrayPredicate(
+ new StringPredicate(entityId),
+ new StringPredicate(attributeName)
+ ));
+ }
+
+ public AttributeRefPredicate(String name, String entityId, String attributeName) {
+ super(
+ new StringPredicate(name),
+ new StringArrayPredicate(
+ new StringPredicate(entityId),
+ new StringPredicate(attributeName)
+ ));
+ }
+
+ public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, String entityId, String attributeName) {
+ this(metaItemDescriptor.getUrn(), entityId, attributeName);
+ }
+
+ public AttributeRefPredicate(StringPredicate name, AttributeRef attributeRef) {
+ super(
+ name,
+ new StringArrayPredicate(
+ new StringPredicate(attributeRef.getEntityId()),
+ new StringPredicate(attributeRef.getAttributeName())
+ ));
+ }
+
+ public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, AttributeRef attributeRef) {
+ this(new StringPredicate(metaItemDescriptor.getUrn()), attributeRef);
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/BooleanPredicate.java b/model/src/main/java/org/openremote/model/query/filter/BooleanPredicate.java
new file mode 100644
index 000000000..2e9c5c6b5
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/BooleanPredicate.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+public class BooleanPredicate implements ValuePredicate<Boolean> {
+
+ public boolean value;
+
+ public BooleanPredicate() {
+ }
+
+ public BooleanPredicate(boolean value) {
+ this.value = value;
+ }
+
+ public static BooleanPredicate fromObjectValue(ObjectValue objectValue) {
+ BooleanPredicate booleanPredicate = new BooleanPredicate();
+ booleanPredicate.value = objectValue
+ .getBoolean("value")
+ .orElseThrow(() -> new IllegalArgumentException("value missing for BooleanPredicate"));
+ return booleanPredicate;
+ }
+
+ public BooleanPredicate value(boolean value) {
+ this.value = value;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "predicate=" + value +
+ '}';
+ }
+
+ @Override
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "BooleanPredicate");
+ objectValue.put("value", Values.create(value));
+ return objectValue;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMNotification.java b/model/src/main/java/org/openremote/model/query/filter/CalendarEventActivePredicate.java
similarity index 66%
rename from manager/src/main/java/org/openremote/manager/notification/FCMNotification.java
rename to model/src/main/java/org/openremote/model/query/filter/CalendarEventActivePredicate.java
index 01f1b522d..e4d986c5d 100644
--- a/manager/src/main/java/org/openremote/manager/notification/FCMNotification.java
+++ b/model/src/main/java/org/openremote/model/query/filter/CalendarEventActivePredicate.java
@@ -17,23 +17,18 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.notification;
+package org.openremote.model.query.filter;
-public class FCMNotification {
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
- protected String title;
- protected String body;
+public class CalendarEventActivePredicate {
- public FCMNotification(String title, String body) {
- this.title = title;
- this.body = body;
- }
-
- public String getTitle() {
- return title;
- }
+ @JsonProperty("timestamp")
+ public long timestampSeconds;
- public String getBody() {
- return body;
+ @JsonCreator
+ public CalendarEventActivePredicate(@JsonProperty("timestamp") long timestampSeconds) {
+ this.timestampSeconds = timestampSeconds;
}
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
new file mode 100644
index 000000000..76dcba4ce
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+public class DateTimePredicate implements ValuePredicate<Long> {
+
+ public String value;
+ public String rangeValue; // Used as upper bound when Operator.BETWEEN
+ public BaseAssetQuery.Operator operator = BaseAssetQuery.Operator.EQUALS;
+ public String dateFormat = "YYYY-MM-DD HH24:MI:SS";//postgres dateformat
+
+ public DateTimePredicate() {
+ }
+
+ public DateTimePredicate(BaseAssetQuery.Operator operator, String value) {
+ this.operator = operator;
+ this.value = value;
+ }
+
+ public DateTimePredicate(String rangeStart, String rangeEnd) {
+ this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.value = rangeStart;
+ this.rangeValue = rangeEnd;
+ }
+
+ public static DateTimePredicate fromObjectValue(ObjectValue objectValue) {
+ DateTimePredicate dateTimePredicate = new DateTimePredicate();
+
+ objectValue.getString("dateFormat").ifPresent(format -> {
+ dateTimePredicate.dateFormat = format;
+ });
+ objectValue.getString("value").ifPresent(value -> {
+ dateTimePredicate.value = value;
+ });
+ objectValue.getString("rangeValue").ifPresent(rangeValue -> {
+ dateTimePredicate.rangeValue = rangeValue;
+ });
+ objectValue.getString("operator").ifPresent(operator -> {
+ dateTimePredicate.operator = BaseAssetQuery.Operator.valueOf(operator);
+ });
+ return dateTimePredicate;
+ }
+
+ public DateTimePredicate operator(BaseAssetQuery.Operator dateMatch) {
+ this.operator = dateMatch;
+ return this;
+ }
+
+ public DateTimePredicate dateFormat(String dateFormat) {
+ this.dateFormat = dateFormat;
+ return this;
+ }
+
+ public DateTimePredicate value(String value) {
+ this.value = value;
+ return this;
+ }
+
+ public DateTimePredicate rangeValue(String rangeEnd) {
+ this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.rangeValue = rangeEnd;
+ return this;
+ }
+
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "StringPredicate");
+ objectValue.put("dateFormat", Values.create(dateFormat));
+ objectValue.put("value", Values.create(value));
+ objectValue.put("rangeValue", Values.create(rangeValue));
+ objectValue.put("operator", Values.create(operator.toString()));
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "value='" + value + '\'' +
+ ", rangeValue='" + rangeValue + '\'' +
+ ", operator =" + operator +
+ ", dateFormat='" + dateFormat + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/LocationPredicate.java b/model/src/main/java/org/openremote/model/query/filter/LocationPredicate.java
new file mode 100644
index 000000000..01fe3eacf
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/LocationPredicate.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = RadialLocationPredicate.class, name = RadialLocationPredicate.name),
+ @JsonSubTypes.Type(value = RectangularLocationPredicate.class, name = RectangularLocationPredicate.name)
+})
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ include = JsonTypeInfo.As.PROPERTY,
+ property = "predicateType"
+)
+
+public abstract class LocationPredicate {
+
+ // TODO: switch return type to location object
+ public abstract double[] getCentrePoint();
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java b/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java
new file mode 100644
index 000000000..251e63981
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+public class NumberPredicate implements ValuePredicate<Double> {
+
+ public double value;
+ public double rangeValue; // Used as upper bound when Operator.BETWEEN
+ public BaseAssetQuery.Operator operator = BaseAssetQuery.Operator.EQUALS;
+ public BaseAssetQuery.NumberType numberType = BaseAssetQuery.NumberType.DOUBLE;
+
+ public NumberPredicate() {
+ }
+
+ public NumberPredicate(double value) {
+ this.value = value;
+ }
+
+ public NumberPredicate(double value, BaseAssetQuery.Operator operator) {
+ this.value = value;
+ this.operator = operator;
+ }
+
+ public NumberPredicate(double value, BaseAssetQuery.NumberType numberType) {
+ this.value = value;
+ this.numberType = numberType;
+ }
+
+ public NumberPredicate(double value, BaseAssetQuery.Operator operator, BaseAssetQuery.NumberType numberType) {
+ this.value = value;
+ this.operator = operator;
+ this.numberType = numberType;
+ }
+
+ public static NumberPredicate fromObjectValue(ObjectValue objectValue) {
+ NumberPredicate numberPredicate = new NumberPredicate();
+ objectValue.getNumber("value").ifPresent(value -> {
+ numberPredicate.value = value;
+ });
+ objectValue.getNumber("rangeValue").ifPresent(rangeValue -> {
+ numberPredicate.rangeValue = rangeValue;
+ });
+ objectValue.getString("operator").ifPresent(operator -> {
+ numberPredicate.operator = BaseAssetQuery.Operator.valueOf(operator);
+ });
+ return numberPredicate;
+ }
+
+ public NumberPredicate predicate(double predicate) {
+ this.value = predicate;
+ return this;
+ }
+
+ public NumberPredicate numberMatch(BaseAssetQuery.Operator operator) {
+ this.operator = operator;
+ return this;
+ }
+
+ public NumberPredicate numberType(BaseAssetQuery.NumberType numberType) {
+ this.numberType = numberType;
+ return this;
+ }
+
+ public NumberPredicate rangeValue(double rangeValue) {
+ this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.rangeValue = rangeValue;
+ return this;
+ }
+
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "StringPredicate");
+ objectValue.put("value", Values.create(value));
+ objectValue.put("rangeValue", Values.create(rangeValue));
+ objectValue.put("operator", Values.create(operator.toString()));
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "value=" + value +
+ ", rangeValue=" + rangeValue +
+ ", operator=" + operator +
+ ", numberType=" + numberType +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/ObjectValueKeyPredicate.java b/model/src/main/java/org/openremote/model/query/filter/ObjectValueKeyPredicate.java
new file mode 100644
index 000000000..e619b4346
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/ObjectValueKeyPredicate.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+public class ObjectValueKeyPredicate implements ValuePredicate<String> {
+
+ public boolean negated;
+ public String key;
+
+ public ObjectValueKeyPredicate(String hasKey) {
+ key = hasKey;
+ }
+
+ public ObjectValueKeyPredicate(String hasKey, boolean negate) {
+ key = hasKey;
+ negated = negate;
+ }
+
+ public ObjectValueKeyPredicate negate() {
+ negated = !negated;
+ return this;
+ }
+
+ @Override
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "ObjectValueKeyPredicate");
+ objectValue.put("negated", Values.create(negated));
+ objectValue.put("key", Values.create(key));
+ return objectValue;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/ParentPredicate.java b/model/src/main/java/org/openremote/model/query/filter/ParentPredicate.java
new file mode 100644
index 000000000..5dfc2de9b
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/ParentPredicate.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.query.BaseAssetQuery;
+
+public class ParentPredicate {
+
+ public String id;
+ public String type;
+ public boolean noParent;
+
+ public ParentPredicate() {
+ }
+
+ public ParentPredicate(String id) {
+ this.id = id;
+ }
+
+ public ParentPredicate(boolean noParent) {
+ this.noParent = noParent;
+ }
+
+ public ParentPredicate id(String id) {
+ this.id = id;
+ return this;
+ }
+
+ public ParentPredicate type(String type) {
+ this.type = type;
+ return this;
+ }
+
+ public ParentPredicate type(AssetType type) {
+ return type(type.getValue());
+ }
+
+ public ParentPredicate noParent(boolean noParent) {
+ this.noParent = noParent;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id='" + id + '\'' +
+ ", type='" + type + '\'' +
+ ", noParent=" + noParent +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMBaseMessage.java b/model/src/main/java/org/openremote/model/query/filter/PathPredicate.java
similarity index 68%
rename from manager/src/main/java/org/openremote/manager/notification/FCMBaseMessage.java
rename to model/src/main/java/org/openremote/model/query/filter/PathPredicate.java
index ced95aff6..79e7b66b2 100644
--- a/manager/src/main/java/org/openremote/manager/notification/FCMBaseMessage.java
+++ b/model/src/main/java/org/openremote/model/query/filter/PathPredicate.java
@@ -17,28 +17,34 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.notification;
+package org.openremote.model.query.filter;
-public class FCMBaseMessage {
+import java.util.Arrays;
- protected String to;
+public class PathPredicate {
- public FCMBaseMessage(String to) {
- this.to = to;
+ public String[] path;
+
+ public PathPredicate() {
+ }
+
+ public PathPredicate(String...path) {
+ this.path = path;
}
- public String getTo() {
- return to;
+ public PathPredicate path(String...path) {
+ this.path = path;
+ return this;
}
- public void setTo(String to) {
- this.to = to;
+ public boolean hasPath() {
+ return path != null && path.length > 0;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "to='" + to + '\'' +
+ "path=" + Arrays.toString(path) +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/RadialLocationPredicate.java b/model/src/main/java/org/openremote/model/query/filter/RadialLocationPredicate.java
new file mode 100644
index 000000000..5c3cb4952
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/RadialLocationPredicate.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Objects;
+
+public class RadialLocationPredicate extends LocationPredicate {
+
+ public static final String name = "radial";
+ public boolean negated;
+ public int radius;
+ public double lat;
+ public double lng;
+
+ @JsonCreator
+ public RadialLocationPredicate(@JsonProperty("radius") int radius,
+ @JsonProperty("lat") double lat,
+ @JsonProperty("lng") double lng,
+ @JsonProperty("negated") boolean negated) {
+ this.radius = radius;
+ this.lat = lat;
+ this.lng = lng;
+ this.negated = negated;
+ }
+
+ public RadialLocationPredicate(@JsonProperty("radius") int radius,
+ @JsonProperty("lat") double lat,
+ @JsonProperty("lng") double lng) {
+ this(radius, lat, lng, false);
+ }
+
+ public RadialLocationPredicate negate() {
+ negated = true;
+ return this;
+ }
+
+ public int getRadius() {
+ return radius;
+ }
+
+ public double getLat() {
+ return lat;
+ }
+
+ public double getLng() {
+ return lng;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RadialLocationPredicate that = (RadialLocationPredicate) o;
+ return negated == that.negated &&
+ radius == that.radius &&
+ Double.compare(that.lat, lat) == 0 &&
+ Double.compare(that.lng, lng) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, negated, radius, lat, lng);
+ }
+
+ @Override
+ public double[] getCentrePoint() {
+ return new double[]{lng, lat};
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/RectangularLocationPredicate.java b/model/src/main/java/org/openremote/model/query/filter/RectangularLocationPredicate.java
new file mode 100644
index 000000000..53cf7e588
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/RectangularLocationPredicate.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Objects;
+
+public class RectangularLocationPredicate extends LocationPredicate {
+
+ public static final String name = "rect";
+ public boolean negated;
+ public double latMin;
+ public double lngMin;
+ public double latMax;
+ public double lngMax;
+
+ @JsonCreator
+ public RectangularLocationPredicate(@JsonProperty("latMin") double latMin,
+ @JsonProperty("lngMin") double lngMin,
+ @JsonProperty("latMax") double latMax,
+ @JsonProperty("lngMax") double lngMax,
+ @JsonProperty("negated") boolean negated) {
+ this.latMin = latMin;
+ this.lngMin = lngMin;
+ this.latMax = latMax;
+ this.lngMax = lngMax;
+ this.negated = negated;
+ }
+
+ public RectangularLocationPredicate(@JsonProperty("latMin") double latMin,
+ @JsonProperty("lngMin") double lngMin,
+ @JsonProperty("latMax") double latMax,
+ @JsonProperty("lngMax") double lngMax) {
+ this(latMin, lngMin, latMax, lngMax, false);
+ }
+
+ public RectangularLocationPredicate negate() {
+ negated = true;
+ return this;
+ }
+
+ public double getLatMin() {
+ return latMin;
+ }
+
+ public double getLngMin() {
+ return lngMin;
+ }
+
+ public double getLatMax() {
+ return latMax;
+ }
+
+ public double getLngMax() {
+ return lngMax;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RectangularLocationPredicate that = (RectangularLocationPredicate) o;
+ return negated == that.negated &&
+ Double.compare(that.latMin, latMin) == 0 &&
+ Double.compare(that.lngMin, lngMin) == 0 &&
+ Double.compare(that.latMax, latMax) == 0 &&
+ Double.compare(that.lngMax, lngMax) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, negated, latMin, lngMin, latMax, lngMax);
+ }
+
+ @Override
+ public double[] getCentrePoint() {
+ double x = (lngMin + lngMax) / 2;
+ double y = (latMin + latMax) / 2;
+ return new double[]{x, y};
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/StringArrayPredicate.java b/model/src/main/java/org/openremote/model/query/filter/StringArrayPredicate.java
new file mode 100644
index 000000000..ad3ea78ca
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/StringArrayPredicate.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+import java.util.Arrays;
+
+public class StringArrayPredicate implements ValuePredicate<String[]> {
+
+ public StringPredicate[] predicates = new StringPredicate[0];
+
+ public StringArrayPredicate() {
+ }
+
+ public StringArrayPredicate(StringPredicate... predicates) {
+ this.predicates = predicates;
+ }
+
+ public static StringArrayPredicate fromObjectValue(ObjectValue objectValue) {
+ StringArrayPredicate stringArrayPredicate = new StringArrayPredicate();
+ objectValue.getArray("value").ifPresent(arrayValue -> {
+ ;
+ stringArrayPredicate.predicates = objectValue.stream()
+ .map(val -> (ObjectValue) val)
+ .map(StringPredicate::fromObjectValue)
+ .toArray(StringPredicate[]::new);
+ });
+ return stringArrayPredicate;
+ }
+
+ public StringArrayPredicate predicates(StringPredicate... predicates) {
+ this.predicates = predicates;
+ return this;
+ }
+
+ @Override
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "StringArrayPredicate");
+ ArrayValue valuesArray = Values.createArray();
+ for (StringPredicate stringPredicate : predicates) {
+ valuesArray.add(stringPredicate.toModelValue());
+ }
+ objectValue.put("value", valuesArray);
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "predicates=" + Arrays.toString(predicates) +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
new file mode 100644
index 000000000..ca900de0a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+import java.util.Locale;
+
+public class StringPredicate implements ValuePredicate<String> {
+
+ public BaseAssetQuery.Match match = BaseAssetQuery.Match.EXACT;
+ public boolean caseSensitive = true;
+ public String value;
+
+ public StringPredicate() {
+ }
+
+ public StringPredicate(String value) {
+ this.value = value;
+ }
+
+ public StringPredicate(BaseAssetQuery.Match match, String value) {
+ this.match = match;
+ this.value = value;
+ }
+
+ public StringPredicate(BaseAssetQuery.Match match, boolean caseSensitive, String value) {
+ this.match = match;
+ this.caseSensitive = caseSensitive;
+ this.value = value;
+ }
+
+ public static StringPredicate fromObjectValue(ObjectValue objectValue) {
+ StringPredicate stringPredicate = new StringPredicate();
+ objectValue.getString("match").ifPresent(match -> {
+ stringPredicate.match = BaseAssetQuery.Match.valueOf(match);
+ });
+ objectValue.getBoolean("caseSensitive").ifPresent(caseSensitive -> {
+ stringPredicate.caseSensitive = caseSensitive;
+ });
+ objectValue.getString("value").ifPresent(value -> {
+ stringPredicate.value = value;
+ });
+ return stringPredicate;
+ }
+
+ public StringPredicate match(BaseAssetQuery.Match match) {
+ this.match = match;
+ return this;
+ }
+
+ public StringPredicate caseSensitive(boolean caseSensitive) {
+ this.caseSensitive = caseSensitive;
+ return this;
+ }
+
+ public StringPredicate value(String value) {
+ this.value = value;
+ return this;
+ }
+
+ public String prepareValue() {
+ String s = match.prepare(this.value);
+ if (!caseSensitive)
+ s = s.toUpperCase(Locale.ROOT);
+ return s;
+ }
+
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "StringPredicate");
+ objectValue.put("match", Values.create(match.toString()));
+ objectValue.put("caseSensitive", Values.create(caseSensitive));
+ objectValue.put("value", Values.create(value));
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "match=" + match +
+ ", caseSensitive=" + caseSensitive +
+ ", value='" + value + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/TenantPredicate.java b/model/src/main/java/org/openremote/model/query/filter/TenantPredicate.java
new file mode 100644
index 000000000..6e1deebcc
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/TenantPredicate.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.query.BaseAssetQuery;
+
+public class TenantPredicate {
+
+ public String realmId;
+ public String realm;
+
+ public TenantPredicate() {
+ }
+
+ public TenantPredicate(String realmId) {
+ this.realmId = realmId;
+ }
+
+ public TenantPredicate realmId(String id) {
+ this.realmId = id;
+ return this;
+ }
+
+ public TenantPredicate realm(String name) {
+ this.realm = name;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "realmId='" + realmId + '\'' +
+ ", realm='" + realm + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/ActionType.java b/model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java
similarity index 71%
rename from model/src/main/java/org/openremote/model/notification/ActionType.java
rename to model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java
index 75b626cd2..5822d823a 100644
--- a/model/src/main/java/org/openremote/model/notification/ActionType.java
+++ b/model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java
@@ -1,4 +1,3 @@
-
/*
* Copyright 2017, OpenRemote Inc.
*
@@ -18,18 +17,20 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.model.notification;
+package org.openremote.model.query.filter;
+
+public class UserAssetPredicate {
+ public String id;
-public enum ActionType {
+ public UserAssetPredicate() {
+ }
- /**
- * Write an attribute, set the given {@link org.openremote.model.attribute.AttributeState}.
- */
- // TODO Rename to ATTRIBUTE_STATE
- ACTUATOR,
+ public UserAssetPredicate(String id) {
+ this.id = id;
+ }
- /**
- * Go to application URL defined in {@link AlertNotification#appUrl}.
- */
- LINK,
-}
\ No newline at end of file
+ public UserAssetPredicate id(String id) {
+ this.id = id;
+ return this;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/notification/DeliveryStatus.java b/model/src/main/java/org/openremote/model/query/filter/ValueEmptyPredicate.java
similarity index 64%
rename from model/src/main/java/org/openremote/model/notification/DeliveryStatus.java
rename to model/src/main/java/org/openremote/model/query/filter/ValueEmptyPredicate.java
index 396ce4f36..d27c4cf8a 100644
--- a/model/src/main/java/org/openremote/model/notification/DeliveryStatus.java
+++ b/model/src/main/java/org/openremote/model/query/filter/ValueEmptyPredicate.java
@@ -17,22 +17,18 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.model.notification;
+package org.openremote.model.query.filter;
-public enum DeliveryStatus {
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
- /**
- * Not delivered to queue.
- */
- PENDING,
+public class ValueEmptyPredicate implements ValuePredicate<Value> {
- /**
- * Delivered to queue for at least one device, device should soon pick it up.
- */
- QUEUED,
-
- /**
- * Picked up by receiving device and dismissed by user.
- */
- ACKNOWLEDGED
+ @Override
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "ValueEmptyPredicate");
+ return objectValue;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/ValueNotEmptyPredicate.java b/model/src/main/java/org/openremote/model/query/filter/ValueNotEmptyPredicate.java
new file mode 100644
index 000000000..72ce2ad94
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/ValueNotEmptyPredicate.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+public class ValueNotEmptyPredicate implements ValuePredicate<Value> {
+
+ @Override
+ public ObjectValue toModelValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("predicateType", "ValueNotEmptyPredicate");
+ return objectValue;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java b/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java
new file mode 100644
index 000000000..e9d8e1f8d
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.query.filter;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.openremote.model.value.ObjectValue;
+
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = StringPredicate.class, name = "string"),
+ @JsonSubTypes.Type(value = BooleanPredicate.class, name = "boolean"),
+ @JsonSubTypes.Type(value = StringArrayPredicate.class, name = "string-array"),
+ @JsonSubTypes.Type(value = DateTimePredicate.class, name = "datetime"),
+ @JsonSubTypes.Type(value = NumberPredicate.class, name = "number")
+})
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ include = JsonTypeInfo.As.PROPERTY,
+ property = "predicateType"
+)
+public interface ValuePredicate<T> {
+
+ ObjectValue toModelValue();
+}
diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.java
index a3befe267..30c83ef69 100644
--- a/model/src/main/java/org/openremote/model/rules/Assets.java
+++ b/model/src/main/java/org/openremote/model/rules/Assets.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.rules;
-import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
import org.openremote.model.value.Value;
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMTargetType.java b/model/src/main/java/org/openremote/model/rules/Notifications.java
similarity index 76%
rename from manager/src/main/java/org/openremote/manager/notification/FCMTargetType.java
rename to model/src/main/java/org/openremote/model/rules/Notifications.java
index 34ae4c81c..07c9e435c 100644
--- a/manager/src/main/java/org/openremote/manager/notification/FCMTargetType.java
+++ b/model/src/main/java/org/openremote/model/rules/Notifications.java
@@ -17,10 +17,14 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.notification;
+package org.openremote.model.rules;
-public enum FCMTargetType {
- DEVICE,
- TOPIC,
- CONDITION
+import org.openremote.model.notification.Notification;
+
+/**
+ * Facade for sending {@link Notification}s from rules RHS.
+ */
+public abstract class Notifications {
+
+ public abstract void send(Notification notification);
}
diff --git a/model/src/main/java/org/openremote/model/rules/Users.java b/model/src/main/java/org/openremote/model/rules/Users.java
index 619c1dea5..67b8bf489 100644
--- a/model/src/main/java/org/openremote/model/rules/Users.java
+++ b/model/src/main/java/org/openremote/model/rules/Users.java
@@ -19,11 +19,10 @@
*/
package org.openremote.model.rules;
-import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.user.UserQuery;
+import org.openremote.model.query.UserQuery;
import java.util.List;
-import java.util.function.Consumer;
+import java.util.stream.Stream;
/**
* Facade for writing rules RHS actions, supporting {@link UserQuery} within the scope
@@ -34,12 +33,8 @@ public abstract class Users {
public abstract class RestrictedQuery extends UserQuery<RestrictedQuery> {
abstract public List<String> getResults();
-
- abstract public void applyResults(Consumer<List<String>> assetIdListConsumer);
}
abstract public RestrictedQuery query();
- abstract public void storeAndNotify(String userId, AlertNotification alert);
-
}
diff --git a/model/src/main/java/org/openremote/model/user/UserQuery.java b/model/src/main/java/org/openremote/model/user/UserQuery.java
deleted file mode 100644
index 6e8cab6fd..000000000
--- a/model/src/main/java/org/openremote/model/user/UserQuery.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.openremote.model.user;
-
-
-public class UserQuery<CHILD extends UserQuery<CHILD>> {
-
- public static class TenantPredicate {
- public String realmId;
- public String realm;
-
- public TenantPredicate() {
- }
-
- public TenantPredicate(String realmId) {
- this.realmId = realmId;
- }
-
- public UserQuery.TenantPredicate realmId(String id) {
- this.realmId = id;
- return this;
- }
-
- public UserQuery.TenantPredicate realm(String name) {
- this.realm = name;
- return this;
- }
- }
-
- public static class AssetPredicate {
- public String id;
-
- public AssetPredicate() {
- }
-
- public AssetPredicate(String id) {
- this.id = id;
- }
-
- public UserQuery.AssetPredicate id(String id) {
- this.id = id;
- return this;
- }
- }
-
- // Restriction predicates
- public UserQuery.TenantPredicate tenantPredicate;
- public UserQuery.AssetPredicate assetPredicate;
-
- public UserQuery() {
- }
-
- @SuppressWarnings("unchecked")
- public CHILD tenant(UserQuery.TenantPredicate tenantPredicate) {
- this.tenantPredicate = tenantPredicate;
- return (CHILD) this;
- }
-
- @SuppressWarnings("unchecked")
- public CHILD asset(UserQuery.AssetPredicate assetPredicate) {
- this.assetPredicate = assetPredicate;
- return (CHILD) this;
- }
-
-}
diff --git a/model/src/main/java/org/openremote/model/util/TimeUtil.java b/model/src/main/java/org/openremote/model/util/TimeUtil.java
index 184e5d0c2..d1fbd93ed 100644
--- a/model/src/main/java/org/openremote/model/util/TimeUtil.java
+++ b/model/src/main/java/org/openremote/model/util/TimeUtil.java
@@ -18,6 +18,8 @@ package org.openremote.model.util;
import javaemul.internal.annotations.GwtIncompatible;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -30,7 +32,7 @@ import java.util.regex.Pattern;
public class TimeUtil {
// Simple syntax
- public static final Pattern SIMPLE = Pattern.compile("([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?");
+ public static final Pattern SIMPLE = Pattern.compile("([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm]$)?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss]$))?\\s*((\\d+)[Ww])?\\s*((\\d+)[Mm][Nn])?\\s*((\\d+)[Yy])?");
private static final int SIM_SGN = 1;
private static final int SIM_DAY = 3;
@@ -38,11 +40,15 @@ public class TimeUtil {
private static final int SIM_MIN = 7;
private static final int SIM_SEC = 9;
private static final int SIM_MS = 11;
+ private static final int SIM_WK = 14;
+ private static final int SIM_MON = 16;
+ private static final int SIM_YR = 18;
private static final long SEC_MS = 1000;
private static final long MIN_MS = 60 * SEC_MS;
private static final long HOU_MS = 60 * MIN_MS;
private static final long DAY_MS = 24 * HOU_MS;
+ private static final long WK_MS = 7 * DAY_MS;
/**
* Parses the given time String and returns the corresponding time in milliseconds
@@ -57,12 +63,21 @@ public class TimeUtil {
if (trimmed.length() > 0) {
Matcher mat = SIMPLE.matcher(trimmed);
if (mat.matches()) {
+ int years = (mat.group(SIM_YR) != null) ? Integer.parseInt(mat.group(SIM_YR)) : 0;
+ int months = (mat.group(SIM_MON) != null) ? Integer.parseInt(mat.group(SIM_MON)) : 0;
+ int weeks = (mat.group(SIM_WK) != null) ? Integer.parseInt(mat.group(SIM_WK)) : 0;
int days = (mat.group(SIM_DAY) != null) ? Integer.parseInt(mat.group(SIM_DAY)) : 0;
int hours = (mat.group(SIM_HOU) != null) ? Integer.parseInt(mat.group(SIM_HOU)) : 0;
int min = (mat.group(SIM_MIN) != null) ? Integer.parseInt(mat.group(SIM_MIN)) : 0;
int sec = (mat.group(SIM_SEC) != null) ? Integer.parseInt(mat.group(SIM_SEC)) : 0;
int ms = (mat.group(SIM_MS) != null) ? Integer.parseInt(mat.group(SIM_MS)) : 0;
- long r = days * DAY_MS + hours * HOU_MS + min * MIN_MS + sec * SEC_MS + ms;
+ long r = weeks * WK_MS + days * DAY_MS + hours * HOU_MS + min * MIN_MS + sec * SEC_MS + ms;
+ if (years != 0 || months != 0) {
+ LocalDateTime dateTime = LocalDateTime.now();
+ LocalDateTime dateTime2 = dateTime.plusMonths(months);
+ dateTime2 = dateTime2.plusYears(years);
+ r += (dateTime2.toEpochSecond(ZoneOffset.UTC) - dateTime.toEpochSecond(ZoneOffset.UTC)) * 1000;
+ }
if (mat.group(SIM_SGN) != null && mat.group(SIM_SGN).equals("-")) {
r = -r;
}
diff --git a/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
index e3d3a06e2..6eda638e9 100644
--- a/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
@@ -168,7 +168,6 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr
def userMapper = new ClientObjectMapper(container.JSON, User.class) as UserMapper
def credentialMapper = new ClientObjectMapper(container.JSON, Credential.class) as CredentialMapper
def roleArrayMapper = new ClientObjectMapper(container.JSON, Role[].class) as RoleArrayMapper
- def deviceTokenMapper = new ClientObjectMapper(container.JSON, List.class) as DeviceNotificationTokenMapper
AdminUserEditActivity adminUserActivity
and: "An activity management configuration"
@@ -200,7 +199,7 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr
},
{
adminUserActivity = new AdminUserEditActivity(
- environment, adminView, adminNavigationPresenter, adminUserView, userResource, userMapper, credentialMapper, roleArrayMapper, notificationResource, deviceTokenMapper
+ environment, adminView, adminNavigationPresenter, adminUserView, userResource, userMapper, credentialMapper, roleArrayMapper, notificationResource
)
return adminUserActivity
},
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
index 8cf6925fe..f40a1ba09 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
@@ -24,6 +24,7 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.*
import org.openremote.model.event.shared.SharedEvent
import org.openremote.model.event.shared.TenantFilter
+import org.openremote.model.query.AssetQuery
import org.openremote.model.security.Tenant
import org.openremote.model.security.TenantResource
import org.openremote.test.*
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 98a9c4e71..464e1c289 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -6,11 +6,13 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetAttribute
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
import org.openremote.model.attribute.AttributeValueType
import org.openremote.model.attribute.Meta
import org.openremote.model.attribute.MetaItem
+import org.openremote.model.query.filter.ParentPredicate
+import org.openremote.model.query.filter.TenantPredicate
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
@@ -22,8 +24,6 @@ import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
-import static org.openremote.model.asset.BaseAssetQuery.ParentPredicate
-import static org.openremote.model.asset.BaseAssetQuery.TenantPredicate
import static org.openremote.model.asset.AssetMeta.*
import static org.openremote.model.attribute.AttributeValueType.BOOLEAN
import static org.openremote.model.attribute.AttributeValueType.NUMBER
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
index 8b71b5712..f896cae2f 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
@@ -10,15 +10,16 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.AssetAttribute
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.attribute.MetaItem
+import org.openremote.model.query.filter.TenantPredicate
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Shared
import spock.lang.Specification
import static org.openremote.model.Constants.MASTER_REALM
-import static org.openremote.model.asset.BaseAssetQuery.*
+import static org.openremote.model.query.BaseAssetQuery.*
import static org.openremote.model.asset.AssetMeta.ACCESS_PUBLIC_READ
import static org.openremote.model.asset.AssetMeta.LABEL
import static org.openremote.model.asset.AssetType.THING
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index fcaac31aa..163ec1386 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -10,14 +10,23 @@ import org.openremote.manager.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetMeta
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
import org.openremote.model.asset.CalendarEventConfiguration
-import org.openremote.model.attribute.AttributeType
import org.openremote.model.calendar.CalendarEvent
import org.openremote.model.calendar.RecurrenceRule
import org.openremote.model.geo.GeoJSONPoint
-import org.openremote.model.value.Values
+import org.openremote.model.query.filter.PathPredicate
+import org.openremote.model.query.filter.AttributeMetaPredicate
+import org.openremote.model.query.filter.AttributePredicate
+import org.openremote.model.query.filter.AttributeRefPredicate
+import org.openremote.model.query.filter.BooleanPredicate
+import org.openremote.model.query.filter.NumberPredicate
+import org.openremote.model.query.filter.ParentPredicate
+import org.openremote.model.query.filter.RadialLocationPredicate
+import org.openremote.model.query.filter.RectangularLocationPredicate
+import org.openremote.model.query.filter.StringPredicate
+import org.openremote.model.query.filter.TenantPredicate
import org.openremote.test.ManagerContainerTrait
import spock.lang.Shared
import spock.lang.Specification
@@ -26,12 +35,11 @@ import spock.util.concurrent.PollingConditions
import javax.persistence.EntityManager
import java.util.function.Function
-import static org.openremote.model.asset.AssetAttribute.createWithDescriptor
-import static org.openremote.model.asset.BaseAssetQuery.*
-import static org.openremote.model.asset.BaseAssetQuery.Access.PRIVATE_READ
-import static org.openremote.model.asset.BaseAssetQuery.Access.RESTRICTED_READ
-import static org.openremote.model.asset.BaseAssetQuery.OrderBy.Property.CREATED_ON
-import static org.openremote.model.asset.BaseAssetQuery.OrderBy.Property.NAME
+import static org.openremote.model.query.BaseAssetQuery.*
+import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ
+import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ
+import static org.openremote.model.query.BaseAssetQuery.OrderBy.Property.CREATED_ON
+import static org.openremote.model.query.BaseAssetQuery.OrderBy.Property.NAME
import static org.openremote.model.asset.AssetType.THING
class AssetQueryTest extends Specification implements ManagerContainerTrait {
@@ -698,7 +706,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets = assetStorageService.findAll(
new AssetQuery()
.select(new Select(Include.ONLY_ID_AND_NAME))
- .location(new RectangularLocationPredicate(51.44540d, 5.46031d, 51.44594d, 5.46110d))
+ .location(new RectangularLocationPredicate(51.44540d, 5.46031d, 51.44594d, 5.46110d))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))
.orderBy(new OrderBy(NAME))
)
diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
index 093875c90..ee8f5e6b5 100644
--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
@@ -1,10 +1,9 @@
package org.openremote.test.console
-import com.google.firebase.messaging.Message
import org.openremote.container.util.UniqueIdentifierGenerator
import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.notification.FCMDeliveryService
import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetStorageService
@@ -14,14 +13,19 @@ import org.openremote.manager.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetResource
-import org.openremote.model.asset.BaseAssetQuery
-import org.openremote.model.attribute.AttributeType
+import org.openremote.model.attribute.AttributeRef
import org.openremote.model.console.ConsoleConfiguration
import org.openremote.model.console.ConsoleProvider
import org.openremote.model.console.ConsoleRegistration
import org.openremote.model.console.ConsoleResource
import org.openremote.model.geo.GeoJSONPoint
-import org.openremote.model.rules.*
+import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.query.filter.RadialLocationPredicate
+import org.openremote.model.rules.AssetRuleset
+import org.openremote.model.rules.RulesResource
+import org.openremote.model.rules.Ruleset
+import org.openremote.model.rules.TenantRuleset
import org.openremote.model.value.ObjectValue
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
@@ -35,42 +39,48 @@ import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_ST
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.SMART_HOME_LOCATION
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.asset.AssetMeta.RULE_STATE
+import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD
+import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl
+import static org.openremote.model.attribute.AttributeType.LOCATION
import static org.openremote.model.util.TextUtil.isNullOrEmpty
import static org.openremote.model.value.Values.parse
class ConsoleTest extends Specification implements ManagerContainerTrait {
def "Check full console behaviour"() {
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)
+ def notificationIds = []
+ def targetTypes = []
+ def targetIds = []
+ def messages = []
+
+ given: "a mock push notification handler"
+ PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
+ isValid() >> true
+
+ // Assume sent to FCM
+ sendMessage(*_) >> {
+ id, targetType, targetId, message ->
+ notificationIds << id
+ targetTypes << targetType
+ targetIds << targetId
+ messages << message
+ return NotificationSendResult.success()
+ }
+ }
- and: "the server container is started"
+ and: "the container environment is started with the mock handler"
+ def conditions = new PollingConditions(timeout: 20, delay: 1)
def serverPort = findEphemeralPort()
ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100
- def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def services = defaultServices()
+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
+ def container = startContainer(defaultConfig(serverPort), services)
def assetStorageService = container.getService(AssetStorageService.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def rulesService = container.getService(RulesService.class)
def rulesetStorageService = container.getService(RulesetStorageService.class)
def geofenceAdapter = (ORConsoleGeofenceAssetAdapter) rulesService.geofenceAssetAdapters.find {it.name == "ORConsole" }
-
- and: "a mock FCM delivery service"
- List<Message> sentFcmMessages = []
- def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {
- // Assume valid
- isValid() >> {
- return true
- }
- // Always "deliver" to FCM
- sendMessage(_) >> {
- Message message ->
- sentFcmMessages.add(message)
- return true
- }
- }
- def notificationService = container.getService(NotificationService)
- notificationService.fcmDeliveryService = mockFCMDeliveryService
Asset testUser3Console1, testUser3Console2, anonymousConsole1
and: "the demo location predicate console rules are loaded"
@@ -291,13 +301,13 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
////////////////////////////////////////////////////
when: "an authenticated user updates the location of a linked console"
- authenticatedAssetResource.writeAttributeValue(null, testUser3Console1.id, AttributeType.LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())
+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console1.id, LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())
then: "the consoles location should have been updated"
conditions.eventually {
def asset = assetStorageService.find(testUser3Console1.id, true)
assert asset != null
- def assetLocation = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.value }.flatMap { GeoJSONPoint.fromValue(it) }.orElse(null)
+ def assetLocation = asset.getAttribute(LOCATION.name).flatMap { it.value }.flatMap { GeoJSONPoint.fromValue(it) }.orElse(null)
assert assetLocation != null
assert assetLocation.x == 0d
assert assetLocation.y == 0d
@@ -305,45 +315,45 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
}
when: "an anonymous user updates the location of a console linked to users"
- anonymousAssetResource.writeAttributeValue(null, testUser3Console1.id, AttributeType.LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())
+ anonymousAssetResource.writeAttributeValue(null, testUser3Console1.id, LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())
then: "the result should be forbidden"
ex = thrown()
ex.response.status == 403
when: "a console's location is updated to be at the smart home"
- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
long timestamp = Long.MAX_VALUE
then: "a welcome home alert should be sent to the console"
conditions.eventually {
- assert sentFcmMessages.size() == 1
+ assert notificationIds.size() == 1
def asset = assetStorageService.find(testUser3Console2.id, true)
assert asset != null
- timestamp = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MAX_VALUE)
+ timestamp = asset.getAttribute(LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MAX_VALUE)
}
when: "a console's location is updated to be at the smart home again"
- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
then: "no more alerts should have been sent"
conditions.eventually {
def asset = assetStorageService.find(testUser3Console2.id, true)
assert asset != null
- assert asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp
- timestamp = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE)
- assert sentFcmMessages.size() == 1
+ assert asset.getAttribute(LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp
+ timestamp = asset.getAttribute(LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE)
+ assert notificationIds.size() == 1
}
when: "a console's location is updated to be null"
- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, "null")
+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.name, "null")
then: "no more alerts should have been sent and the welcome reset rule should have fired on the tenant rule engine"
conditions.eventually {
def asset = assetStorageService.find(testUser3Console2.id, true)
assert asset != null
- assert asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp
- assert sentFcmMessages.size() == 1
+ assert asset.getAttribute(LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp
+ assert notificationIds.size() == 1
def customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
@@ -351,11 +361,11 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
}
when: "a console's location is updated to be at the smart home again"
- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())
then: "another alert should have been sent"
conditions.eventually {
- assert sentFcmMessages.size() == 2
+ assert notificationIds.size() == 2
}
///////////////////////////////////////
@@ -364,7 +374,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
when: "the geofences of a user linked console are requested by the authenticated user"
def geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)
- def expectedLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(100, SMART_HOME_LOCATION.y, SMART_HOME_LOCATION.x)
+ def expectedLocationPredicate = new RadialLocationPredicate(100, SMART_HOME_LOCATION.y, SMART_HOME_LOCATION.x)
then: "the welcome home geofence should be retrieved"
assert expectedLocationPredicate.centrePoint.size() == 2
@@ -375,8 +385,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofences[0].lat == expectedLocationPredicate.lat
assert geofences[0].lng == expectedLocationPredicate.lng
assert geofences[0].radius == expectedLocationPredicate.radius
- assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, testUser3Console1.id)
+ assert geofences[0].httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofences[0].url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
when: "an anonymous user tries to retrieve the geofences of a console linked to users"
geofences = anonymousRulesResource.getAssetGeofences(null, testUser3Console1.id)
@@ -394,8 +404,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofences[0].lat == expectedLocationPredicate.lat
assert geofences[0].lng == expectedLocationPredicate.lng
assert geofences[0].radius == expectedLocationPredicate.radius
- assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, testUser3Console2.id)
+ assert geofences[0].httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofences[0].url == getWriteAttributeUrl(new AttributeRef(testUser3Console2.id, LOCATION.getName()))
when: "the geofences of anonymousConsole1 are retrieved"
geofences = anonymousRulesResource.getAssetGeofences(null, anonymousConsole1.id)
@@ -406,8 +416,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofences[0].lat == expectedLocationPredicate.lat
assert geofences[0].lng == expectedLocationPredicate.lng
assert geofences[0].radius == expectedLocationPredicate.radius
- assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, anonymousConsole1.id)
+ assert geofences[0].httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofences[0].url == getWriteAttributeUrl(new AttributeRef(anonymousConsole1.id, LOCATION.getName()))
when: "the geofences of a non-existent console are retrieved"
geofences = anonymousRulesResource.getAssetGeofences(null, UniqueIdentifierGenerator.generateId("nonExistentConsole"))
@@ -438,7 +448,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
)
newRuleset = rulesetStorageService.merge(newRuleset)
RulesEngine consoleParentEngine = null
- def newLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(50, 0, -60)
+ def newLocationPredicate = new RadialLocationPredicate(50, 0, -60)
then: "the new rule engine should be created and be running"
conditions.eventually {
@@ -453,9 +463,9 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences"
conditions.eventually {
- assert sentFcmMessages.size() == 4
- assert sentFcmMessages[2].data.get("action") == "GEOFENCE_REFRESH"
- assert sentFcmMessages[3].data.get("action") == "GEOFENCE_REFRESH"
+ assert notificationIds.size() == 4
+ assert ((PushNotificationMessage)messages[2]).data.getString("action").orElse(null) == "GEOFENCE_REFRESH"
+ assert ((PushNotificationMessage)messages[3]).data.getString("action").orElse(null) == "GEOFENCE_REFRESH"
}
then: "the geofences of testUser3Console1 should contain the welcome home geofence and new radial geofence (but not the rectangular and duplicate predicates)"
@@ -470,29 +480,25 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofence1.lat == expectedLocationPredicate.lat
assert geofence1.lng == expectedLocationPredicate.lng
assert geofence1.radius == expectedLocationPredicate.radius
- assert geofence1.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofence1.url == String.format(
- ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,
- testUser3Console1.id)
+ assert geofence1.httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofence1.url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
assert geofence2.lat == newLocationPredicate.lat
assert geofence2.lng == newLocationPredicate.lng
assert geofence2.radius == newLocationPredicate.radius
- assert geofence2.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofence2.url == String.format(
- ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,
- testUser3Console1.id)
+ assert geofence2.httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofence2.url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
}
when: "an existing ruleset containing a radial location predicate is updated"
newRuleset.rules = getClass().getResource("/org/openremote/test/rules/BasicLocationPredicates2.groovy").text
newRuleset = rulesetStorageService.merge(newRuleset)
- newLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(150, 10, 40)
+ newLocationPredicate = new RadialLocationPredicate(150, 10, 40)
then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences"
conditions.eventually {
- assert sentFcmMessages.size() == 6
- assert sentFcmMessages[4].data.get("action") == "GEOFENCE_REFRESH"
- assert sentFcmMessages[5].data.get("action") == "GEOFENCE_REFRESH"
+ assert notificationIds.size() == 6
+ assert ((PushNotificationMessage)messages[4]).data.getString("action").orElse(null) == "GEOFENCE_REFRESH"
+ assert ((PushNotificationMessage)messages[5]).data.getString("action").orElse(null) == "GEOFENCE_REFRESH"
}
then: "the geofences of testUser3Console1 should still contain two geofences but the location of the second should have been updated"
@@ -507,17 +513,13 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofence1.lat == expectedLocationPredicate.lat
assert geofence1.lng == expectedLocationPredicate.lng
assert geofence1.radius == expectedLocationPredicate.radius
- assert geofence1.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofence1.url == String.format(
- ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,
- testUser3Console1.id)
+ assert geofence1.httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofence1.url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
assert geofence2.lat == newLocationPredicate.lat
assert geofence2.lng == newLocationPredicate.lng
assert geofence2.radius == newLocationPredicate.radius
- assert geofence2.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofence2.url == String.format(
- ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,
- testUser3Console1.id)
+ assert geofence2.httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofence2.url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
}
when: "a location predicate ruleset is removed"
@@ -532,14 +534,12 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert geofences[0].lat == expectedLocationPredicate.lat
assert geofences[0].lng == expectedLocationPredicate.lng
assert geofences[0].radius == expectedLocationPredicate.radius
- assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD
- assert geofences[0].url == String.format(
- ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,
- testUser3Console1.id)
+ assert geofences[0].httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert geofences[0].url == getWriteAttributeUrl(new AttributeRef(testUser3Console1.id, LOCATION.getName()))
}
when: "the RULE_STATE meta is removed from a console's location attribute"
- testUser3Console1.getAttribute(AttributeType.LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == RULE_STATE.urn})
+ testUser3Console1.getAttribute(LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == RULE_STATE.urn})
testUser3Console1 = assetStorageService.merge(testUser3Console1)
then: "no geofences should remain for this console"
diff --git a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
index bc5e71de2..bc38d6415 100644
--- a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
@@ -1,5 +1,7 @@
package org.openremote.test.failure
+import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesFacts
import org.openremote.manager.rules.RulesService
@@ -8,6 +10,9 @@ import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.setup.SetupService
import org.openremote.manager.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.notification.AbstractNotificationMessage
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.NotificationSendResult
import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.Ruleset
import org.openremote.model.rules.TenantRuleset
@@ -125,71 +130,78 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaine
stopContainer(container)
}
- def "Rule action calls users facade with invalid user ID in asset ruleset"() {
+ def "Rule action calls users facade with out of scope query"() {
+
+ ArrayList<String> notificationIds = []
+ ArrayList<Notification.TargetType> targetTypes = []
+ ArrayList<String> targetIds = []
+ ArrayList<AbstractNotificationMessage> messages = []
+
+ given: "a mock push notification handler"
+ PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
+ isValid() >> true
+
+ // Assume sent to FCM
+ sendMessage(*_) >> {
+ id, targetType, targetId, message ->
+ notificationIds << id
+ targetTypes << targetType
+ targetIds << targetId
+ messages << message
+ return NotificationSendResult.success()
+ }
+ }
- given: "the container environment is started"
+ and: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 20, delay: 1)
def serverPort = findEphemeralPort()
- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
+ def services = defaultServices()
+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def rulesService = container.getService(RulesService.class)
def rulesetStorageService = container.getService(RulesetStorageService.class)
- RulesEngine apartment2Engine
and: "some rules"
Ruleset ruleset = new AssetRuleset(
"Failure Ruleset",
managerDemoSetup.apartment2Id,
- getClass().getResource("/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy").text,
+ getClass().getResource("/org/openremote/test/failure/RulesFailureUserQueryTenantException.groovy").text,
Ruleset.Lang.GROOVY
)
ruleset = rulesetStorageService.merge(ruleset)
- expect: "the rule engines to become available and be running"
+ expect: "the rule engine to become available and be in an error state"
conditions.eventually {
- apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)
+ def apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)
assert apartment2Engine != null
assert apartment2Engine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR
assert apartment2Engine.deployments[ruleset.id].error instanceof RuntimeException
assert apartment2Engine.deployments[ruleset.id].error.message ==
- "Error executing action of rule 'Notify non-existent user': User not linked to asset RulesEngineId{scope=AssetRuleset, realmId='" + keycloakDemoSetup.customerATenant.id + "', assetId='" + managerDemoSetup.apartment2Id + "'}: doesnotexist"
+ "Error executing action of rule 'Notify master user out of scope': Overriding query restriction is not allowed in this rules scope"
assert apartment2Engine.isError()
assert apartment2Engine.getError() instanceof RuntimeException
assert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")
}
- cleanup: "stop the container"
- stopContainer(container)
- }
-
- def "Rule action calls users facade with invalid user ID in tenant ruleset"() {
-
- given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 20, delay: 1)
- def serverPort = findEphemeralPort()
- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
- def rulesService = container.getService(RulesService.class)
- def rulesetStorageService = container.getService(RulesetStorageService.class)
- RulesEngine customerAEngine
-
- and: "some rules"
- Ruleset ruleset = new TenantRuleset(
- "Failure Ruleset",
- keycloakDemoSetup.customerATenant.id,
- getClass().getResource("/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy").text,
- Ruleset.Lang.GROOVY
+ when: "the same rules are deployed in a tenant ruleset"
+ ruleset = new TenantRuleset(
+ "Failure Ruleset",
+ keycloakDemoSetup.customerATenant.id,
+ getClass().getResource("/org/openremote/test/failure/RulesFailureUserQueryTenantException.groovy").text,
+ Ruleset.Lang.GROOVY
)
ruleset = rulesetStorageService.merge(ruleset)
- expect: "the rule engines to become available and be running"
+ then: "the rule engine to become available and be in an error state"
conditions.eventually {
- customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
+ def customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR
assert customerAEngine.deployments[ruleset.id].error instanceof RuntimeException
- assert customerAEngine.deployments[ruleset.id].error.message == "Error executing action of rule 'Notify non-existent user': User not in tenant RulesEngineId{scope=TenantRuleset, realmId='" + keycloakDemoSetup.customerATenant.id + "', assetId='null'}: doesnotexist"
+ assert customerAEngine.deployments[ruleset.id].error.message ==
+ "Error executing action of rule 'Notify master user out of scope': Overriding query restriction is not allowed in this rules scope"
assert customerAEngine.isError()
assert customerAEngine.getError() instanceof RuntimeException
assert customerAEngine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")
diff --git a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
similarity index 70%
rename from test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
rename to test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index 2454955af..2020847d3 100644
--- a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -1,20 +1,16 @@
-package org.openremote.test.user
+package org.openremote.test.notification
-import com.google.firebase.messaging.Message
import org.openremote.container.timer.TimerService
-import org.openremote.manager.notification.FCMBaseMessage
-import org.openremote.manager.notification.FCMDeliveryService
import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.setup.SetupService
import org.openremote.manager.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.notification.NotificationResource
-import org.openremote.model.notification.ActionType
-import org.openremote.model.notification.AlertAction
-import org.openremote.model.notification.AlertNotification
-import org.openremote.model.notification.DeliveryStatus
-import org.openremote.model.user.UserQuery
+import org.openremote.model.notification.*
+import org.openremote.model.query.UserQuery
+import org.openremote.model.query.filter.UserAssetPredicate
import org.openremote.test.ManagerContainerTrait
+import spock.lang.Shared
import spock.lang.Specification
import javax.ws.rs.WebApplicationException
@@ -22,34 +18,40 @@ import javax.ws.rs.WebApplicationException
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
-import static org.openremote.model.Constants.MASTER_REALM
-import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
+import static org.openremote.model.Constants.*
-class NotificationServiceTest extends Specification implements ManagerContainerTrait {
+class NotificationTest extends Specification implements ManagerContainerTrait {
def "Store notification tokens for user devices"() {
- given: "the server container is started"
+ def notificationIds = []
+ def targetTypes = []
+ def targetIds = []
+ def messages = []
+
+ given: "a mock push notification handler"
+ PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
+ isValid() >> true
+
+ // Assume sent to FCM
+ sendMessage(*_) >> {
+ id, targetType, targetId, message ->
+ notificationIds << id
+ targetTypes << targetType
+ targetIds << targetId
+ messages << message
+ return NotificationSendResult.success()
+ }
+ }
+
+ and: "the container environment is started with the mock handler"
def serverPort = findEphemeralPort()
- def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def services = defaultServices()
+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
+ def container = startContainer(defaultConfig(serverPort), services)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
- and: "a mock FCM delivery service"
- def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {
- // Assume valid
- isValid() >> {
- return true
- }
- // Always "deliver" to FCM
- sendMessage(_ as Message) >> {
- return true
- }
- }
- def notificationService = container.getService(NotificationService)
- notificationService.fcmDeliveryService = mockFCMDeliveryService
-
and: "an authenticated test user"
def realm = "customerA"
def testuser3AccessToken = authenticate(
@@ -76,13 +78,13 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
).token
- def notification = new AlertNotification(
+ def notification = new PushNotificationMessage(
title: "The Title",
appUrl: '#test',
message: "Message",
)
- def alertAction = new AlertAction()
+ def alertAction = new PushNotificationAction()
alertAction.setTitle("TEST_ACTION")
alertAction.setActionType(ActionType.ACTUATOR)
@@ -119,22 +121,22 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
notificationService.findAllUsersWithToken().size() == 1
def foundUser = notificationService.findAllUsersWithToken().first()
foundUser == keycloakDemoSetup.testuser3Id
-
- and: "must find registered test user if limiting to same tenant"
- notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).size() == 1
- def foundUser2 = notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).first()
- foundUser2 == keycloakDemoSetup.testuser3Id
-
- and: "must not find registered test user if limiting to different tenant"
- notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerBTenant.id))).isEmpty()
+//
+// and: "must find registered test user if limiting to same tenant"
+// notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).size() == 1
+// def foundUser2 = notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).first()
+// foundUser2 == keycloakDemoSetup.testuser3Id
+//
+// and: "must not find registered test user if limiting to different tenant"
+// notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerBTenant.id))).isEmpty()
and: "must find registered test user if limiting to asset user has access to"
- notificationService.findAllUsersWithToken(new UserQuery().asset(new UserQuery.AssetPredicate().id(managerDemoSetup.apartment1Id))).size() == 1
- def foundUser3 = notificationService.findAllUsersWithToken(new UserQuery().asset(new UserQuery.AssetPredicate().id(managerDemoSetup.apartment1Id))).first()
+ notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment1Id))).size() == 1
+ def foundUser3 = notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment1Id))).first()
foundUser3 == keycloakDemoSetup.testuser3Id
and: "must not find registered test user if limiting to asset user has not access to"
- notificationService.findAllUsersWithToken(new UserQuery().asset(new UserQuery.AssetPredicate().id(managerDemoSetup.apartment3Id))).isEmpty()
+ notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment3Id))).isEmpty()
when: "the notification token of some device is updated"
testuser3NotificationResource.storeDeviceToken(null, "device456", "token789", "ANDROID")
@@ -145,7 +147,7 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
notificationService.findAllTokenForUser(keycloakDemoSetup.testuser3Id).size() == 2
when: "the notification is stored"
- testuser3NotificationResource.storeNotificationForCurrentUser(null, notification)
+ testuser3NotificationResource.sendNotification(null, notification)
def alerts = testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null)
then: "it should be one notification pending"
@@ -159,20 +161,20 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
ex.response.status == 403
when: "a user tries to acknowledge a notification she doesn't own"
- testuser2NotificationResource.ackNotificationOfCurrentUser(null, alerts.get(0).id)
+ testuser2NotificationResource.notificationAcknowledged(null, alerts.get(0).id)
then: "an exception should be thrown"
ex = thrown()
ex.response.status == 403
when: "the notification is acknowledged"
- testuser3NotificationResource.ackNotificationOfCurrentUser(null, alerts.get(0).id)
+ testuser3NotificationResource.notificationAcknowledged(null, alerts.get(0).id)
then: "there should be no alert"
testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null).size() == 0
when: "the notification is stored"
- testuser3NotificationResource.storeNotificationForCurrentUser(null, notification)
+ testuser3NotificationResource.sendNotification(null, notification)
alerts = adminNotificationResource.getNotificationsOfUser(null, keycloakDemoSetup.testuser3Id)
then: "it should be one notification queued"
@@ -185,7 +187,7 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
}
when: "all notifications of the user are removed"
- adminNotificationResource.removeNotificationsOfUser(null, keycloakDemoSetup.testuser3Id)
+ adminNotificationResource.removeNotifications(null, keycloakDemoSetup.testuser3Id)
then: "there should be no alert"
testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null).size() == 0
diff --git a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
index 1bcd0e151..2934612e7 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
@@ -9,7 +9,7 @@ import org.openremote.manager.setup.SetupService
import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetAttribute
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
import org.openremote.model.asset.agent.AgentLink
import org.openremote.model.attribute.AttributeEvent
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy
similarity index 98%
rename from test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy
rename to test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy
index dc0f31d23..418b71334 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy
@@ -18,7 +18,7 @@ import spock.util.concurrent.PollingConditions
import static java.util.concurrent.TimeUnit.SECONDS
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_2
-class ResidenceAllLighgtsOffTest extends Specification implements ManagerContainerTrait {
+class ResidenceAllLightsOffTest extends Specification implements ManagerContainerTrait {
def "Turn all lights off"() {
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 5858b6245..93afaa28e 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -1,22 +1,24 @@
package org.openremote.test.rules.residence
-import com.google.firebase.messaging.Message
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.notification.FCMDeliveryService
import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetStorageService
+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
import org.openremote.manager.setup.SetupService
-import org.openremote.manager.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.attribute.AttributeEvent
-import org.openremote.model.notification.ActionType
-import org.openremote.model.notification.AlertAction
-import org.openremote.model.notification.NotificationResource
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.console.ConsoleProvider
+import org.openremote.model.console.ConsoleRegistration
+import org.openremote.model.console.ConsoleResource
+import org.openremote.model.notification.*
import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.Ruleset
+import org.openremote.model.value.ObjectValue
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
@@ -26,16 +28,40 @@ import java.util.concurrent.TimeUnit
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
+import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD
+import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl
+import static org.openremote.model.value.Values.parse
class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerContainerTrait {
def "Trigger notification when presence is detected and alarm enabled"() {
- given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 15, delay: 1)
+ def notificationIds = []
+ def targetTypes = []
+ def targetIds = []
+ def messages = []
+
+ given: "a mock push notification handler"
+ PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
+ isValid() >> true
+
+ // Assume sent to FCM
+ sendMessage(*_) >> {
+ id, targetType, targetId, message ->
+ notificationIds << id
+ targetTypes << targetType
+ targetIds << targetId
+ messages << message
+ return NotificationSendResult.success()
+ }
+ }
+
+ and: "the container environment is started with the mock handler"
+ def conditions = new PollingConditions(timeout: 20, delay: 1)
def serverPort = findEphemeralPort()
- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def services = defaultServices()
+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def rulesService = container.getService(RulesService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
@@ -43,20 +69,6 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
def rulesetStorageService = container.getService(RulesetStorageService.class)
RulesEngine apartment1Engine
- and: "a mock FCM delivery service"
- def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {
- // Assume valid
- isValid() >> {
- return true
- }
- // Always "deliver" to FCM
- sendMessage(_ as Message) >> {
- return true
- }
- }
- def notificationService = container.getService(NotificationService)
- notificationService.fcmDeliveryService = mockFCMDeliveryService
-
and: "some rules"
Ruleset ruleset = new AssetRuleset(
"Demo Apartment - Notify Alarm Trigger",
@@ -90,14 +102,36 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
"testuser3"
).token
- and: "the notification resource"
- def notificationResource = getClientTarget(serverUri(serverPort), realm, accessToken).proxy(NotificationResource.class)
-
- when: "the notification tokens of some devices are stored"
- notificationResource.storeDeviceToken(null, "device123", "token123", "ANDROID")
-
- then: "the tokens should be in the database"
- notificationService.findDeviceToken("device123", keycloakDemoSetup.testuser3Id).get().token == "token123"
+ and: "the notification and console resources"
+ def authenticatedConsoleResource = getClientTarget(serverUri(serverPort), realm, accessToken).proxy(ConsoleResource.class)
+
+ when: "a console is registered by the test user"
+ def consoleRegistration = new ConsoleRegistration(null,
+ "Test Console",
+ "1.0",
+ "Android 7.0",
+ new HashMap<String, ConsoleProvider>() {
+ {
+ put("geofence", new ConsoleProvider(
+ ORConsoleGeofenceAssetAdapter.NAME,
+ true,
+ false,
+ false,
+ null
+ ))
+ put("push", new ConsoleProvider(
+ "fcm",
+ true,
+ true,
+ false,
+ (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)
+ ))
+ }
+ })
+ def returnedConsoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)
+
+ then: "the console should be registered"
+ assert returnedConsoleRegistration.id != null
when: "the alarm is enabled"
assetProcessingService.sendAttributeEvent(new AttributeEvent(
@@ -123,13 +157,25 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
and: "the user should be notified"
conditions.eventually {
- def alerts = notificationResource.getQueuedNotificationsOfCurrentUser(null)
- assert alerts.size() == 1
- assert alerts[0].title == "Apartment Alarm"
- assert alerts[0].message.startsWith("Aanwezigheid in Living Room")
- assert alerts[0].actions.length() == 2
- assert alerts[0].actions.getObject(0).orElse(null) == new AlertAction("Details", ActionType.LINK, "#security").objectValue
- assert alerts[0].actions.getObject(1).orElse(null) == new AlertAction("Alarm uit", ActionType.ACTUATOR, managerDemoSetup.apartment1Id, "alarmEnabled", Values.create(false).toJson()).objectValue
+ assert notificationIds.size() == 1
+ assert targetTypes[0] == Notification.TargetType.ASSET
+ assert targetIds[0] == returnedConsoleRegistration.id
+ def pushMessage = (PushNotificationMessage) messages[0]
+ assert pushMessage.title == "Apartment Alarm"
+ assert pushMessage.body.startsWith("Aanwezigheid in Living Room")
+ assert pushMessage.buttons.size() == 2
+ assert pushMessage.buttons[0].title == "Details"
+ assert pushMessage.buttons[0].action.url == "#security"
+ assert pushMessage.buttons[0].action.httpMethod == null
+ assert pushMessage.buttons[0].action.data == null
+ assert !pushMessage.buttons[0].action.openInBrowser
+ assert !pushMessage.buttons[0].action.silent
+ assert pushMessage.buttons[1].title == "Alarm uit"
+ assert pushMessage.buttons[1].action.url == getWriteAttributeUrl(new AttributeRef(managerDemoSetup.apartment1Id, "alarmEnabled"))
+ assert pushMessage.buttons[1].action.httpMethod == WRITE_ATTRIBUTE_HTTP_METHOD
+ assert !Values.getBoolean(pushMessage.buttons[1].action.data).orElse(true)
+ assert !pushMessage.buttons[1].action.openInBrowser
+ assert pushMessage.buttons[1].action.silent
}
when: "time moves on and other events happen that trigger evaluation in the rule engine"
@@ -138,24 +184,22 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(444), getClockTimeOf(container)
))
- then: "we have still only one notification pending"
+ then: "still only one notification should have been sent"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert asset.getAttribute("co2Level").get().valueAsInteger.orElse(null) == 444
- def alerts = notificationResource.getQueuedNotificationsOfCurrentUser(null)
- assert alerts.size() == 1
+ assert notificationIds.size() == 1
}
- when: "time moves on"
+ when: "time moves on more than the alarm silence duration"
advancePseudoClock(30, TimeUnit.MINUTES, container)
- then: "we notify again and now have two notifications pending"
+ then: "another notification should be sent"
conditions.eventually {
- def alerts = notificationResource.getQueuedNotificationsOfCurrentUser(null)
- assert alerts.size() == 2
+ assert notificationIds.size() == 2
}
- when: "the presence os no longer in Living room of apartment 1"
+ when: "the presence is no longer triggered in Living room of apartment 1"
advancePseudoClock(5, TimeUnit.SECONDS, container)
assetProcessingService.sendAttributeEvent(new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceDetected", Values.create(false), getClockTimeOf(container)
@@ -170,10 +214,9 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
when: "time moves on"
advancePseudoClock(40, TimeUnit.MINUTES, container)
- then: "we have still only two notifications pending"
+ then: "still only two notifications should have been sent"
conditions.eventually {
- def alerts = notificationResource.getQueuedNotificationsOfCurrentUser(null)
- assert alerts.size() == 2
+ assert notificationIds.size() == 2
}
cleanup: "the server should be stopped"
diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy
deleted file mode 100644
index 1d1ad97b1..000000000
--- a/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.openremote.test.rules
-
-import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.notification.AlertNotification
-import org.openremote.model.rules.Users
-
-RulesBuilder rules = binding.rules
-Users users = binding.users
-
-rules.add()
- .name("Notify non-existent user")
- .when(
- { facts ->
- true
- })
- .then(
- { facts ->
- users.storeAndNotify("doesnotexist", new AlertNotification("Foo", "Bar"))
- })
diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy
index bd55c8a2e..2131a91f3 100644
--- a/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy
+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.failure
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
RulesBuilder rules = binding.rules
diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureUserQueryTenantException.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureUserQueryTenantException.groovy
new file mode 100644
index 000000000..80632efd3
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureUserQueryTenantException.groovy
@@ -0,0 +1,42 @@
+package org.openremote.test.failure
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.PushNotificationAction
+import org.openremote.model.notification.PushNotificationButton
+import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.query.filter.TenantPredicate
+import org.openremote.model.rules.Notifications
+import org.openremote.model.rules.Users
+import org.openremote.model.value.Values
+
+RulesBuilder rules = binding.rules
+Users users = binding.users
+Notifications notifications = binding.notifications
+
+rules.add()
+ .name("Notify master user out of scope")
+ .when(
+ { facts ->
+ return !facts.getOptional("fired").isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("fired", true)
+
+ def userQuery = users.query()
+ userQuery.tenantPredicate = new TenantPredicate("master")
+ def targetUsers = userQuery.getResults()
+
+ Notification notification = new Notification(
+ "ApartmentAlarm",
+ new PushNotificationMessage()
+ .setTitle("False Alarm")
+ .setBody("This alarm should not be sent"),
+ new Notification.Targets(Notification.TargetType.USER, targetUsers)
+ )
+
+ // Send the notification to non existent user
+ notifications.send(notification)
+ })
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovy
index 1ff8f3e64..e53935116 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovy
@@ -2,8 +2,9 @@ package org.openremote.test.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.asset.AssetQuery
-import org.openremote.model.asset.BaseAssetQuery
+import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.filter.RadialLocationPredicate
+import org.openremote.model.query.filter.RectangularLocationPredicate
RulesBuilder rules = binding.rules
@@ -11,7 +12,7 @@ rules.add()
.name("Another radial location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(50, 0, -60))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RadialLocationPredicate(50, 0, -60))).isPresent() &&
!facts.matchFirst("RadialLocation2").isPresent()
})
.then(
@@ -23,7 +24,7 @@ rules.add()
.name("Duplicate radial location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&
!facts.matchFirst("DuplicateLocation").isPresent()
})
.then(
@@ -35,7 +36,7 @@ rules.add()
.name("Rectangular location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&
!facts.matchFirst("RectLocation").isPresent()
})
.then(
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy
index 84c2907be..32db053e1 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy
@@ -2,8 +2,9 @@ package org.openremote.test.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.asset.AssetQuery
-import org.openremote.model.asset.BaseAssetQuery
+import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.filter.RadialLocationPredicate
+import org.openremote.model.query.filter.RectangularLocationPredicate
RulesBuilder rules = binding.rules
@@ -11,7 +12,7 @@ rules.add()
.name("Another radial location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(150, 10, 40))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RadialLocationPredicate(150, 10, 40))).isPresent() &&
!facts.matchFirst("RadialLocation2").isPresent()
})
.then(
@@ -23,7 +24,7 @@ rules.add()
.name("Duplicate radial location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&
!facts.matchFirst("Location").isPresent()
})
.then(
@@ -35,7 +36,7 @@ rules.add()
.name("Rectangular location predicate")
.when(
{ facts ->
- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().location(new RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&
!facts.matchFirst("RectLocation").isPresent()
})
.then(
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy
index dc862aeb4..d71a7cd5c 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
RulesBuilder rules = binding.rules
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy
index eb9fdc769..239ee21de 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy
@@ -3,7 +3,7 @@
package org.openremote.test.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
RulesBuilder rules = binding.rules
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
index 08456825c..2e45bf43a 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.AssetQuery
+import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
import org.openremote.model.attribute.AttributeValueType