Search in sources :

Example 11 with AssetQuery

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;
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) Arrays(java.util.Arrays) AbstractNotificationMessage(org.openremote.model.notification.AbstractNotificationMessage) KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED(org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED) EmailPopulatingBuilder(org.simplejavamail.email.EmailPopulatingBuilder) TransportStrategy(org.simplejavamail.mailer.config.TransportStrategy) MapAccess.getInteger(org.openremote.container.util.MapAccess.getInteger) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Notification(org.openremote.model.notification.Notification) UserQuery(org.openremote.model.query.UserQuery) Recipient(org.simplejavamail.email.Recipient) org.openremote.model.query.filter(org.openremote.model.query.filter) EmailNotificationMessage(org.openremote.model.notification.EmailNotificationMessage) MapAccess.getBoolean(org.openremote.container.util.MapAccess.getBoolean) TextUtil(org.openremote.model.util.TextUtil) NotificationSendResult(org.openremote.model.notification.NotificationSendResult) User(org.openremote.model.security.User) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) MailerBuilder(org.simplejavamail.mailer.MailerBuilder) AssetQuery(org.openremote.model.query.AssetQuery) Mailer(org.simplejavamail.mailer.Mailer) ContainerService(org.openremote.model.ContainerService) Logger(java.util.logging.Logger) Constants(org.openremote.model.Constants) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) List(java.util.List) EmailBuilder(org.simplejavamail.email.EmailBuilder) Email(org.simplejavamail.email.Email) Collections(java.util.Collections) EmailNotificationMessage(org.openremote.model.notification.EmailNotificationMessage) User(org.openremote.model.security.User) AssetQuery(org.openremote.model.query.AssetQuery) ArrayList(java.util.ArrayList) Recipient(org.simplejavamail.email.Recipient) Notification(org.openremote.model.notification.Notification) UserQuery(org.openremote.model.query.UserQuery) Asset(org.openremote.model.asset.Asset)

Example 12 with AssetQuery

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))));
        }
    }
}
Also used : GatewayDisconnectEvent(org.openremote.model.gateway.GatewayDisconnectEvent) AssetQuery(org.openremote.model.query.AssetQuery) TenantPredicate(org.openremote.model.query.filter.TenantPredicate) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SharedEvent(org.openremote.model.event.shared.SharedEvent) EventRequestResponseWrapper(org.openremote.model.event.shared.EventRequestResponseWrapper)

Example 13 with AssetQuery

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()));
        });
    }
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) Tenant(org.openremote.model.security.Tenant) IntStream(java.util.stream.IntStream) ManagerKeycloakIdentityProvider(org.openremote.manager.security.ManagerKeycloakIdentityProvider) java.util(java.util) GATEWAY(org.openremote.model.syslog.SyslogCategory.GATEWAY) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Exchange(org.apache.camel.Exchange) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) Level(java.util.logging.Level) Predicate(org.apache.camel.Predicate) RulesetStorageService(org.openremote.manager.rules.RulesetStorageService) RulesService(org.openremote.manager.rules.RulesService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) User(org.openremote.model.security.User) Ruleset(org.openremote.model.rules.Ruleset) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) GatewayDisconnectEvent(org.openremote.model.gateway.GatewayDisconnectEvent) AssetQuery(org.openremote.model.query.AssetQuery) GatewayAsset(org.openremote.model.asset.impl.GatewayAsset) ContainerService(org.openremote.model.ContainerService) EntityManager(javax.persistence.EntityManager) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) Consumer(java.util.function.Consumer) ClientEventService(org.openremote.manager.event.ClientEventService) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) GatewayConnector.mapAssetId(org.openremote.manager.gateway.GatewayConnector.mapAssetId) org.openremote.model.attribute(org.openremote.model.attribute) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) PredicateBuilder.and(org.apache.camel.builder.PredicateBuilder.and) PredicateBuilder.or(org.apache.camel.builder.PredicateBuilder.or) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) ConnectionConstants(org.openremote.container.web.ConnectionConstants) SharedEvent(org.openremote.model.event.shared.SharedEvent) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) GatewayAsset(org.openremote.model.asset.impl.GatewayAsset) GatewayAsset(org.openremote.model.asset.impl.GatewayAsset)

Example 14 with AssetQuery

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);
}
Also used : AssetQuery(org.openremote.model.query.AssetQuery)

Example 15 with AssetQuery

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;
    }
}
Also used : AssetRuleset(org.openremote.model.rules.AssetRuleset) PathPredicate(org.openremote.model.query.filter.PathPredicate) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) TenantPredicate(org.openremote.model.query.filter.TenantPredicate)

Aggregations

AssetQuery (org.openremote.model.query.AssetQuery)17 Asset (org.openremote.model.asset.Asset)9 Level (java.util.logging.Level)8 Logger (java.util.logging.Logger)8 Collectors (java.util.stream.Collectors)8 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)7 java.util (java.util)6 RouteBuilder (org.apache.camel.builder.RouteBuilder)6 MessageBrokerService (org.openremote.container.message.MessageBrokerService)6 AssetStorageService (org.openremote.manager.asset.AssetStorageService)6 Container (org.openremote.model.Container)6 TextUtil (org.openremote.model.util.TextUtil)6 EntityManager (javax.persistence.EntityManager)5 PERSISTENCE_TOPIC (org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC)5 PersistenceService.isPersistenceEventForEntityType (org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType)5 TimerService (org.openremote.container.timer.TimerService)5 ClientEventService (org.openremote.manager.event.ClientEventService)5 GatewayService (org.openremote.manager.gateway.GatewayService)5 ContainerService (org.openremote.model.ContainerService)5 AttributeEvent (org.openremote.model.attribute.AttributeEvent)5