Search in sources :

Example 1 with TimerService

use of org.openremote.container.timer.TimerService in project openremote by openremote.

the class Main method main.

public static void main(String[] args) throws Exception {
    List<ContainerService> services = new ArrayList<ContainerService>() {

        {
            addAll(Arrays.asList(new TimerService(), new ManagerExecutorService(), new I18NService(), new ManagerPersistenceService(), new MessageBrokerSetupService(), new ManagerIdentityService(), new SetupService(), new ClientEventService(), new RulesetStorageService(), new RulesService(), new AssetStorageService(), new AssetDatapointService(), new AssetAttributeLinkingService(), new AssetProcessingService(), new MessageBrokerService()));
            ServiceLoader.load(Protocol.class).forEach(this::add);
            addAll(Arrays.asList(new AgentService(), new SimulatorService(), new MapService(), new NotificationService(), new ConsoleAppService(), new ManagerWebService()));
        }
    };
    new Container(services).startBackground();
}
Also used : MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) AssetStorageService(org.openremote.manager.asset.AssetStorageService) ConsoleAppService(org.openremote.manager.apps.ConsoleAppService) ArrayList(java.util.ArrayList) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) TimerService(org.openremote.container.timer.TimerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) Container(org.openremote.container.Container) AgentService(org.openremote.manager.agent.AgentService) RulesService(org.openremote.manager.rules.RulesService) ManagerWebService(org.openremote.manager.web.ManagerWebService) SimulatorService(org.openremote.manager.simulator.SimulatorService) ClientEventService(org.openremote.manager.event.ClientEventService) Protocol(org.openremote.agent.protocol.Protocol) MapService(org.openremote.manager.map.MapService) RulesetStorageService(org.openremote.manager.rules.RulesetStorageService) I18NService(org.openremote.manager.i18n.I18NService) ManagerPersistenceService(org.openremote.manager.persistence.ManagerPersistenceService) NotificationService(org.openremote.manager.notification.NotificationService) AssetAttributeLinkingService(org.openremote.manager.asset.AssetAttributeLinkingService) ManagerExecutorService(org.openremote.manager.concurrent.ManagerExecutorService) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) SetupService(org.openremote.manager.setup.SetupService) ContainerService(org.openremote.container.ContainerService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 2 with TimerService

use of org.openremote.container.timer.TimerService in project openremote by openremote.

the class AssetProcessingService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    identityService = container.getService(ManagerIdentityService.class);
    persistenceService = container.getService(PersistenceService.class);
    rulesService = container.getService(RulesService.class);
    agentService = container.getService(AgentService.class);
    assetStorageService = container.getService(AssetStorageService.class);
    assetDatapointService = container.getService(AssetDatapointService.class);
    assetAttributeLinkingService = container.getService(AssetAttributeLinkingService.class);
    messageBrokerService = container.getService(MessageBrokerService.class);
    clientEventService = container.getService(ClientEventService.class);
    clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {
        if (!subscription.isEventType(AttributeEvent.class)) {
            return false;
        }
        // Always must have a filter, as you can't subscribe to ALL asset attribute events
        if (subscription.getFilter() != null && subscription.getFilter() instanceof AttributeEvent.EntityIdFilter) {
            AttributeEvent.EntityIdFilter filter = (AttributeEvent.EntityIdFilter) subscription.getFilter();
            // Superuser can get attribute events for any asset
            if (auth.isSuperUser())
                return true;
            // Regular user must have role
            if (!auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
                return false;
            }
            boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());
            // Client can subscribe to several assets
            for (String assetId : filter.getEntityId()) {
                Asset asset = assetStorageService.find(assetId);
                // If the asset doesn't exist, subscription must fail
                if (asset == null)
                    return false;
                if (isRestrictedUser) {
                    // Restricted users can only get attribute events for their linked assets
                    if (!assetStorageService.isUserAsset(auth.getUserId(), assetId))
                        return false;
                // TODO Restricted clients should only receive events for RESTRICTED_READ attributes!
                } else {
                    // Regular users can only get attribute events for assets in their realm
                    if (!asset.getTenantRealm().equals(auth.getAuthenticatedRealm()))
                        return false;
                }
            }
            return true;
        }
        return false;
    });
    processors.add(agentService);
    processors.add(rulesService);
    processors.add(assetDatapointService);
    processors.add(assetAttributeLinkingService);
    container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
}
Also used : TimerService(org.openremote.container.timer.TimerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) PersistenceService(org.openremote.container.persistence.PersistenceService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) AgentService(org.openremote.manager.agent.AgentService) RulesService(org.openremote.manager.rules.RulesService) Asset(org.openremote.model.asset.Asset) ClientEventService(org.openremote.manager.event.ClientEventService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 3 with TimerService

use of org.openremote.container.timer.TimerService in project openremote by openremote.

the class AbstractProtocol method start.

@Override
public void start(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    executorService = container.getExecutorService();
    assetService = container.getService(ProtocolAssetService.class);
    predictedAssetService = container.getService(ProtocolPredictedAssetService.class);
    messageBrokerContext = container.getService(MessageBrokerService.class).getContext();
    withLock(getProtocolName() + "::start", () -> {
        try {
            messageBrokerContext.addRoutes(new RouteBuilder() {

                @Override
                public void configure() throws Exception {
                    from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName() + getAgent().getId()).process(exchange -> {
                        Protocol<?> protocolInstance = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, Protocol.class);
                        if (protocolInstance != AbstractProtocol.this) {
                            return;
                        }
                        AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
                        Attribute<?> linkedAttribute = getLinkedAttributes().get(event.getAttributeRef());
                        if (linkedAttribute == null) {
                            LOG.info("Attempt to write to attribute that is not actually linked to this protocol '" + AbstractProtocol.this + "': " + linkedAttribute);
                            return;
                        }
                        processLinkedAttributeWrite(event);
                    });
                }
            });
            doStart(container);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });
    this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();
}
Also used : Protocol(org.openremote.model.asset.agent.Protocol) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) AttributeRef(org.openremote.model.attribute.AttributeRef) HashMap(java.util.HashMap) AgentLink(org.openremote.model.asset.agent.AgentLink) HashSet(java.util.HashSet) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ProducerTemplate(org.apache.camel.ProducerTemplate) SyslogCategory(org.openremote.model.syslog.SyslogCategory) MessageBrokerService(org.openremote.container.message.MessageBrokerService) AttributeState(org.openremote.model.attribute.AttributeState) MetaItemType(org.openremote.model.value.MetaItemType) Pair(org.openremote.model.util.Pair) Set(java.util.Set) Logger(java.util.logging.Logger) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) TimeUnit(java.util.concurrent.TimeUnit) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) MessageBrokerContext(org.openremote.container.message.MessageBrokerContext) Agent(org.openremote.model.asset.agent.Agent) GlobalLock(org.openremote.container.concurrent.GlobalLock) ProtocolUtil.hasDynamicWriteValue(org.openremote.model.protocol.ProtocolUtil.hasDynamicWriteValue) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) RouteBuilder(org.apache.camel.builder.RouteBuilder) Attribute(org.openremote.model.attribute.Attribute) Protocol(org.openremote.model.asset.agent.Protocol) TimerService(org.openremote.container.timer.TimerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent)

Example 4 with TimerService

use of org.openremote.container.timer.TimerService in project openremote by openremote.

the class ClientEventService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    messageBrokerService = container.getService(MessageBrokerService.class);
    identityService = container.getService(ManagerIdentityService.class);
    gatewayService = container.getService(GatewayService.class);
    eventSubscriptions = new EventSubscriptions(container.getService(TimerService.class));
    messageBrokerService.getContext().getTypeConverterRegistry().addTypeConverters(new EventTypeConverters());
    // TODO: Remove prefix and just use event type then use a subscription wrapper to pass subscription ID around
    messageBrokerService.getContext().addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("websocket://" + WEBSOCKET_EVENTS).routeId("FromClientWebsocketEvents").process(exchange -> exchange.getIn().setHeader(HEADER_CONNECTION_TYPE, HEADER_CONNECTION_TYPE_WEBSOCKET)).to(ClientEventService.CLIENT_EVENT_QUEUE).end();
            from(ClientEventService.CLIENT_EVENT_QUEUE).routeId("ClientEvents").choice().when(header(ConnectionConstants.SESSION_OPEN)).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                sessionKeyInfoMap.put(sessionKey, createSessionInfo(sessionKey, exchange));
                passToInterceptors(exchange);
            }).stop().when(or(header(ConnectionConstants.SESSION_CLOSE), header(ConnectionConstants.SESSION_CLOSE_ERROR))).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                sessionKeyInfoMap.remove(sessionKey);
                eventSubscriptions.cancelAll(sessionKey);
                passToInterceptors(exchange);
            }).stop().end().process(exchange -> {
                // Do basic formatting of exchange
                EventRequestResponseWrapper<?> requestResponse = null;
                if (exchange.getIn().getBody() instanceof EventRequestResponseWrapper) {
                    requestResponse = exchange.getIn().getBody(EventRequestResponseWrapper.class);
                } else if (exchange.getIn().getBody() instanceof String && exchange.getIn().getBody(String.class).startsWith(EventRequestResponseWrapper.MESSAGE_PREFIX)) {
                    requestResponse = exchange.getIn().getBody(EventRequestResponseWrapper.class);
                }
                if (requestResponse != null) {
                    SharedEvent event = requestResponse.getEvent();
                    exchange.getIn().setHeader(HEADER_REQUEST_RESPONSE_MESSAGE_ID, requestResponse.getMessageId());
                    exchange.getIn().setBody(event);
                }
                if (exchange.getIn().getBody() instanceof String) {
                    String bodyStr = exchange.getIn().getBody(String.class);
                    if (bodyStr.startsWith(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX)) {
                        exchange.getIn().setBody(exchange.getIn().getBody(EventSubscription.class));
                    } else if (bodyStr.startsWith(CancelEventSubscription.MESSAGE_PREFIX)) {
                        exchange.getIn().setBody(exchange.getIn().getBody(CancelEventSubscription.class));
                    } else if (bodyStr.startsWith(SharedEvent.MESSAGE_PREFIX)) {
                        exchange.getIn().setBody(exchange.getIn().getBody(SharedEvent.class));
                    }
                }
                if (exchange.getIn().getBody() instanceof SharedEvent) {
                    SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
                    // If there is no timestamp in event, set to system time
                    if (event.getTimestamp() <= 0) {
                        event.setTimestamp(timerService.getCurrentTimeMillis());
                    }
                }
            }).process(exchange -> passToInterceptors(exchange)).choice().when(body().isInstanceOf(EventSubscription.class)).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                EventSubscription<?> subscription = exchange.getIn().getBody(EventSubscription.class);
                AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
                boolean restrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext);
                boolean anonymousUser = authContext == null;
                String username = authContext == null ? "anonymous" : authContext.getUsername();
                String realm = exchange.getIn().getHeader(Constants.REALM_PARAM_NAME, String.class);
                if (authorizeEventSubscription(realm, authContext, subscription)) {
                    eventSubscriptions.createOrUpdate(sessionKey, restrictedUser, anonymousUser, subscription);
                    subscription.setSubscribed(true);
                    sendToSession(sessionKey, subscription);
                } else {
                    LOG.warning("Unauthorized subscription from '" + username + "' in realm '" + realm + "': " + subscription);
                    sendToSession(sessionKey, new UnauthorizedEventSubscription<>(subscription));
                }
            }).stop().when(body().isInstanceOf(CancelEventSubscription.class)).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
            }).stop().when(body().isInstanceOf(SharedEvent.class)).choice().when(// Inbound messages from clients
            header(HEADER_CONNECTION_TYPE).isNotNull()).to(ClientEventService.CLIENT_EVENT_TOPIC).stop().when(// Outbound message to clients
            header(HEADER_CONNECTION_TYPE).isNull()).split(method(eventSubscriptions, "splitForSubscribers")).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                sendToSession(sessionKey, exchange.getIn().getBody());
            }).stop().endChoice().otherwise().process(exchange -> LOG.info("Unsupported message body: " + exchange.getIn().getBody())).end();
        }
    });
    // Add pending internal subscriptions
    if (!pendingInternalSubscriptions.isEmpty()) {
        pendingInternalSubscriptions.forEach(subscription -> eventSubscriptions.createOrUpdate(INTERNAL_SESSION_KEY, false, false, subscription));
    }
    pendingInternalSubscriptions = null;
}
Also used : java.util(java.util) AuthContext(org.openremote.container.security.AuthContext) CloseReason(javax.websocket.CloseReason) Exchange(org.apache.camel.Exchange) Level(java.util.logging.Level) Builder.header(org.apache.camel.builder.Builder.header) ManagerWebService(org.openremote.manager.web.ManagerWebService) MessageBrokerService(org.openremote.container.message.MessageBrokerService) Session(javax.websocket.Session) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) ContainerService(org.openremote.model.ContainerService) SESSION_TERMINATOR(org.openremote.container.web.ConnectionConstants.SESSION_TERMINATOR) Constants(org.openremote.model.Constants) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Logger(java.util.logging.Logger) Container(org.openremote.model.Container) Consumer(java.util.function.Consumer) SyslogEvent(org.openremote.model.syslog.SyslogEvent) MqttBrokerService(org.openremote.manager.mqtt.MqttBrokerService) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) org.openremote.model.event.shared(org.openremote.model.event.shared) PredicateBuilder.or(org.apache.camel.builder.PredicateBuilder.or) ConnectionConstants(org.openremote.container.web.ConnectionConstants) GatewayService(org.openremote.manager.gateway.GatewayService) RouteBuilder(org.apache.camel.builder.RouteBuilder) AuthContext(org.openremote.container.security.AuthContext) TimerService(org.openremote.container.timer.TimerService) GatewayService(org.openremote.manager.gateway.GatewayService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 5 with TimerService

use of org.openremote.container.timer.TimerService in project openremote by openremote.

the class AssetStorageService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    persistenceService = container.getService(PersistenceService.class);
    identityService = container.getService(ManagerIdentityService.class);
    clientEventService = container.getService(ClientEventService.class);
    gatewayService = container.getService(GatewayService.class);
    EventSubscriptionAuthorizer assetEventAuthorizer = AssetStorageService.assetInfoAuthorizer(identityService, this);
    clientEventService.addSubscriptionAuthorizer((realm, auth, subscription) -> {
        if (!subscription.isEventType(AssetEvent.class)) {
            return false;
        }
        return assetEventAuthorizer.authorise(realm, auth, subscription);
    });
    container.getService(ManagerWebService.class).addApiSingleton(new AssetResourceImpl(container.getService(TimerService.class), identityService, this, container.getService(MessageBrokerService.class)));
    container.getService(ManagerWebService.class).addApiSingleton(new ConsoleResourceImpl(container.getService(TimerService.class), identityService, this, clientEventService));
    container.getService(MessageBrokerService.class).getContext().addRoutes(this);
}
Also used : PersistenceService(org.openremote.container.persistence.PersistenceService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) EventSubscriptionAuthorizer(org.openremote.manager.event.EventSubscriptionAuthorizer) ManagerWebService(org.openremote.manager.web.ManagerWebService) ConsoleResourceImpl(org.openremote.manager.asset.console.ConsoleResourceImpl) ClientEventService(org.openremote.manager.event.ClientEventService) TimerService(org.openremote.container.timer.TimerService) GatewayService(org.openremote.manager.gateway.GatewayService)

Aggregations

TimerService (org.openremote.container.timer.TimerService)9 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)8 MessageBrokerService (org.openremote.container.message.MessageBrokerService)5 ClientEventService (org.openremote.manager.event.ClientEventService)5 ManagerWebService (org.openremote.manager.web.ManagerWebService)5 PersistenceService (org.openremote.container.persistence.PersistenceService)4 AssetStorageService (org.openremote.manager.asset.AssetStorageService)3 AssetDatapointService (org.openremote.manager.datapoint.AssetDatapointService)3 GatewayService (org.openremote.manager.gateway.GatewayService)3 Logger (java.util.logging.Logger)2 RouteBuilder (org.apache.camel.builder.RouteBuilder)2 AgentService (org.openremote.manager.agent.AgentService)2 MqttBrokerService (org.openremote.manager.mqtt.MqttBrokerService)2 RulesService (org.openremote.manager.rules.RulesService)2 Container (org.openremote.model.Container)2 AttributeEvent (org.openremote.model.attribute.AttributeEvent)2 java.util (java.util)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1