use of org.openremote.model.query.AssetQuery in project openremote by openremote.
the class EmailNotificationHandler method getTargets.
@Override
public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> targets, AbstractNotificationMessage message) {
List<Notification.Target> mappedTargets = new ArrayList<>();
if (targets != null) {
targets.forEach(target -> {
Notification.TargetType targetType = target.getType();
String targetId = target.getId();
switch(targetType) {
case TENANT:
case USER:
// Find all users in this tenant or by id
User[] users = targetType == Notification.TargetType.TENANT ? managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().tenant(new TenantPredicate(targetId))) : managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().ids(targetId));
if (users.length == 0) {
if (targetType == Notification.TargetType.USER) {
LOG.info("User not found: " + targetId);
} else {
LOG.info("No users found in target realm: " + targetId);
}
return;
}
mappedTargets.addAll(Arrays.stream(users).filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))).map(user -> {
Notification.Target userAssetTarget = new Notification.Target(Notification.TargetType.USER, user.getId());
userAssetTarget.setData(new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail()));
return userAssetTarget;
}).collect(Collectors.toList()));
break;
case CUSTOM:
// Nothing to do here
mappedTargets.add(new Notification.Target(targetType, targetId));
break;
case ASSET:
// Find descendant assets with email attribute
List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().attributes(Asset.EMAIL.getName())).paths(new PathPredicate(targetId)).attributes(new AttributePredicate(new StringPredicate(Asset.EMAIL.getName()), new ValueEmptyPredicate().negate(true))));
if (assets.isEmpty()) {
LOG.fine("No assets with email attribute descendants of target asset");
return;
}
mappedTargets.addAll(assets.stream().map(asset -> {
Notification.Target assetTarget = new Notification.Target(Notification.TargetType.ASSET, asset.getId());
assetTarget.setData(new EmailNotificationMessage.Recipient(asset.getName(), asset.getEmail().orElse(null)));
return assetTarget;
}).collect(Collectors.toList()));
break;
}
});
}
EmailNotificationMessage email = (EmailNotificationMessage) message;
// Map to/cc/bcc into a custom target for traceability in sent notifications
List<String> addresses = new ArrayList<>();
if (email.getTo() != null) {
addresses.addAll(email.getTo().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "to:" + address).collect(Collectors.toList()));
email.setTo((List<EmailNotificationMessage.Recipient>) null);
}
if (email.getCc() != null) {
addresses.addAll(email.getCc().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "cc:" + address).collect(Collectors.toList()));
email.setCc((List<EmailNotificationMessage.Recipient>) null);
}
if (email.getBcc() != null) {
addresses.addAll(email.getBcc().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "bcc:" + address).collect(Collectors.toList()));
email.setBcc((List<EmailNotificationMessage.Recipient>) null);
}
if (!addresses.isEmpty()) {
mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, String.join(";", addresses)));
}
return mappedTargets;
}
use of org.openremote.model.query.AssetQuery in project openremote by openremote.
the class GatewayClientService method onCentralManagerMessage.
protected void onCentralManagerMessage(GatewayConnection connection, String message) {
String messageId = null;
SharedEvent event = null;
if (message.startsWith(EventRequestResponseWrapper.MESSAGE_PREFIX)) {
EventRequestResponseWrapper<?> wrapper = messageFromString(message, EventRequestResponseWrapper.MESSAGE_PREFIX, EventRequestResponseWrapper.class);
messageId = wrapper.getMessageId();
event = wrapper.getEvent();
}
if (message.startsWith(SharedEvent.MESSAGE_PREFIX)) {
event = messageFromString(message, SharedEvent.MESSAGE_PREFIX, SharedEvent.class);
}
if (event != null) {
if (event instanceof GatewayDisconnectEvent) {
if (((GatewayDisconnectEvent) event).getReason() == GatewayDisconnectEvent.Reason.PERMANENT_ERROR) {
LOG.info("Central manager requested disconnect due to permanent error (likely this version of the edge gateway software is not compatible with that manager version)");
destroyGatewayClient(connection, clientRealmMap.get(connection.getLocalRealm()));
clientRealmMap.put(connection.getLocalRealm(), null);
}
} else if (event instanceof AttributeEvent) {
assetProcessingService.sendAttributeEvent((AttributeEvent) event, AttributeEvent.Source.INTERNAL);
} else if (event instanceof AssetEvent) {
AssetEvent assetEvent = (AssetEvent) event;
if (assetEvent.getCause() == AssetEvent.Cause.CREATE || assetEvent.getCause() == AssetEvent.Cause.UPDATE) {
Asset asset = assetEvent.getAsset();
asset.setRealm(connection.getLocalRealm());
LOG.finer("Request from central manager to create/update an asset: Realm=" + connection.getLocalRealm() + ", Asset<?> ID=" + asset.getId());
try {
asset = assetStorageService.merge(asset, true);
} catch (Exception e) {
LOG.log(Level.INFO, "Request from central manager to create/update an asset failed: Realm=" + connection.getLocalRealm() + ", Asset<?> ID=" + asset.getId(), e);
}
}
} else if (event instanceof DeleteAssetsRequestEvent) {
DeleteAssetsRequestEvent deleteRequest = (DeleteAssetsRequestEvent) event;
LOG.finer("Request from central manager to delete asset(s): Realm=" + connection.getLocalRealm() + ", Asset<?> IDs=" + Arrays.toString(deleteRequest.getAssetIds().toArray()));
boolean success = false;
try {
success = assetStorageService.delete(deleteRequest.getAssetIds());
} catch (Exception e) {
LOG.log(Level.INFO, "Request from central manager to create/update an asset failed: Realm=" + connection.getLocalRealm() + ", Asset<?> IDs=" + Arrays.toString(deleteRequest.getAssetIds().toArray()), e);
} finally {
sendCentralManagerMessage(connection.getLocalRealm(), messageToString(EventRequestResponseWrapper.MESSAGE_PREFIX, new EventRequestResponseWrapper<>(messageId, new DeleteAssetsResponseEvent(success, deleteRequest.getAssetIds()))));
}
} else if (event instanceof ReadAssetsEvent) {
ReadAssetsEvent readAssets = (ReadAssetsEvent) event;
AssetQuery query = readAssets.getAssetQuery();
// Force realm to be the one that this client is associated with
query.tenant(new TenantPredicate(connection.getLocalRealm()));
List<Asset<?>> assets = assetStorageService.findAll(readAssets.getAssetQuery());
sendCentralManagerMessage(connection.getLocalRealm(), messageToString(EventRequestResponseWrapper.MESSAGE_PREFIX, new EventRequestResponseWrapper<>(messageId, new AssetsEvent(assets))));
}
}
}
use of org.openremote.model.query.AssetQuery in project openremote by openremote.
the class GatewayService method start.
@Override
public void start(Container container) throws Exception {
if (!active) {
return;
}
List<GatewayAsset> gateways = assetStorageService.findAll(new AssetQuery().types(GatewayAsset.class)).stream().map(asset -> (GatewayAsset) asset).collect(Collectors.toList());
List<String> gatewayIds = gateways.stream().map(Asset::getId).collect(Collectors.toList());
gateways = gateways.stream().filter(gateway -> Arrays.stream(gateway.getPath()).noneMatch(p -> !p.equals(gateway.getId()) && gatewayIds.contains(p))).collect(Collectors.toList());
if (!gateways.isEmpty()) {
LOG.info("Directly registered gateways found = " + gateways.size());
gateways.forEach(gateway -> {
// Check if client has been created
boolean hasClientId = gateway.getClientId().isPresent();
boolean hasClientSecret = gateway.getClientSecret().isPresent();
if (!hasClientId || !hasClientSecret) {
createUpdateGatewayServiceUser(gateway);
}
// Create connector
GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, gateway);
gatewayConnectorMap.put(gateway.getId().toLowerCase(Locale.ROOT), connector);
// Get IDs of all assets under this gateway
List<Asset<?>> gatewayAssets = assetStorageService.findAll(new AssetQuery().parents(gateway.getId()).select(new AssetQuery.Select().excludeAttributes()).recursive(true));
gatewayAssets.forEach(asset -> assetIdGatewayIdMap.put(asset.getId(), gateway.getId()));
});
}
}
use of org.openremote.model.query.AssetQuery in project openremote by openremote.
the class GatewayConnector method startSync.
/**
* Get list of gateway assets (get basic details and then batch load them to minimise load)
*/
protected synchronized void startSync() {
if (syncAborted()) {
return;
}
expectedSyncResponseName = ASSET_READ_EVENT_NAME_INITIAL;
sendMessageToGateway(new EventRequestResponseWrapper<>(ASSET_READ_EVENT_NAME_INITIAL, new ReadAssetsEvent(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).recursive(true))));
syncProcessorFuture = executorService.schedule(this::onSyncAssetsTimeout, SYNC_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
}
use of org.openremote.model.query.AssetQuery in project openremote by openremote.
the class AssetsFacade method getResults.
@Override
public Stream<Asset<?>> getResults(AssetQuery assetQuery) {
if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
// Realm is restricted to rules
assetQuery.tenant = new TenantPredicate(rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId)));
} else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
// Realm is restricted to assets'
assetQuery.tenant = new TenantPredicate(rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId)));
Asset<?> restrictedAsset = assetStorageService.find(rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId)), true);
if (restrictedAsset == null) {
throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
}
assetQuery.paths(new PathPredicate(restrictedAsset.getPath()));
}
AssetQuery.Select oldValue = assetQuery.select;
assetQuery.select = new AssetQuery.Select().excludeAttributes();
try {
return assetStorageService.findAll(assetQuery).stream();
} finally {
assetQuery.select = oldValue;
}
}
Aggregations